package com.xbongbong.parent.abstracts;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.formula.constant.Constant;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.help.SharePermissionHelp;
import com.xbongbong.paas.help.team.FormTeamSetHelp;
import com.xbongbong.paas.help.team.TeamUserHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.pojo.InfoArrPojo;
import com.xbongbong.paas.log.thread.LogThreadPoolBeanConfig;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.vo.UserFormPermissionVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.pojo.PermissionTermsPojo;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.interfaces.TeamStrategy;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailDTO;
import com.xbongbong.pro.detailtab.pojo.team.CoopUserPojo;
import com.xbongbong.pro.detailtab.pojo.team.HistoryCoInfoPojo;
import com.xbongbong.pro.detailtab.pojo.team.IndependentCoPermissionPojo;
import com.xbongbong.pro.detailtab.pojo.team.IsolationUserPermissionPojo;
import com.xbongbong.pro.detailtab.pojo.team.MainUserPojo;
import com.xbongbong.pro.detailtab.pojo.team.ShareUserPermissionPojo;
import com.xbongbong.pro.detailtab.pojo.team.TeamGroupPojo;
import com.xbongbong.pro.detailtab.pojo.team.TeamRelatedPojo;
import com.xbongbong.pro.detailtab.pojo.team.TeamUserPojo;
import com.xbongbong.pro.detailtab.pojo.team.UserLabelPojo;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailIsolationVO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailShareVO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailVO;
import com.xbongbong.pro.detailtab.vo.team.TeamListBatchPermissionVO;
import com.xbongbong.pro.domain.entity.FormLabelEntity;
import com.xbongbong.pro.domain.entity.FormTeamSetEntity;
import com.xbongbong.pro.domain.entity.SysLabelEntity;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.FieldAdvanceOperationEnum;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.BuinessDefaultErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.UserTeamErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.HandoverPermissionAliasEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.enums.permission.enums.UpdateProPermissionAliasEnum;
import com.xbongbong.pro.enums.teammembers.enums.CoUserPermissionEnum;
import com.xbongbong.pro.enums.teammembers.enums.FormCoUserDefaultPermissionEnum;
import com.xbongbong.pro.enums.teammembers.enums.FormDefaultPatternEnum;
import com.xbongbong.pro.enums.teammembers.enums.FormOwnerUniqueEnum;
import com.xbongbong.pro.enums.teammembers.enums.FormPatternEnum;
import com.xbongbong.pro.enums.teammembers.enums.OwnerUniqueDefaultEnum;
import com.xbongbong.pro.formdata.pojo.AfterSavePojo;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.listbatch.pojo.TeamBatchPojo;
import com.xbongbong.pro.log.pojo.DetailLogPojo;
import com.xbongbong.pro.model.FormLabelModel;
import com.xbongbong.pro.model.SysLabelModel;
import com.xbongbong.pro.permission.pojo.dto.VerifyUpdatePermissionDTO;
import com.xbongbong.pro.team.TeamAfterFormatDTO;
import com.xbongbong.pro.team.TeamAfterModeProcessPOJO;
import com.xbongbong.pro.team.TeamAfterVerifyDTO;
import com.xbongbong.pro.team.TeamFieldExplainPOJO;
import com.xbongbong.pro.team.TeamModelProcessMidPOJO;
import com.xbongbong.pro.team.TeamUserListPOJO;
import com.xbongbong.pro.team.TeamVerifyDTO;
import com.xbongbong.pro.team.pojo.TeamSaveMiddlePojo;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ListBatchConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.constant.teammembers.TeamMembersConstant;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.domain.entity.ext.WorkOrderFormEntityExt;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.SaasBatchEnum;
import com.xbongbong.saas.enums.UserTeamEnum;
import com.xbongbong.saas.enums.UserTeamOperateTagEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.base.ManagementBaseEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.dictionary.PublicEnum;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.DataPermissionEnum;
import com.xbongbong.sys.enums.LabelTypeEnum;
import com.xbongbong.sys.model.UserModel;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;

/**
 * @author 吴峰
 * @date 2022/11/09 14:38
 */
@Service("abstractParentTeamStrategy")
public abstract class AbstractParentTeamStrategy implements TeamStrategy {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractParentTeamStrategy.class);
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private UserModel userModel;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private UserTeamHelp userTeamHelp;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private SysLabelModel sysLabelModel;
    @Resource
    private FormLabelModel formLabelModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private LogThreadPoolBeanConfig logThreadPoolBeanConfig;
    @Resource
    private FormTeamSetHelp formTeamSetHelp;
    @Resource
    private TeamUserHelp teamUserHelp;
    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private SharePermissionHelp sharePermissionHelp;

    @Override
    public void beforeVerifyUserTeam(ValidateDataDTO validateDataDTO) throws XbbException {
        Integer saasMark = validateDataDTO.getSaasMark();
        TeamVerifyDTO teamVerifyDTO = new TeamVerifyDTO();
        BeanUtil.copyProperties(validateDataDTO, teamVerifyDTO);
        boolean isNew = Objects.isNull(validateDataDTO.getDataId()) || Objects.equals(validateDataDTO.getDataId(), 0L);
        String creatorId = StringUtil.isNotEmpty(validateDataDTO.getCreatorId()) ? validateDataDTO.getCreatorId() : validateDataDTO.getUserId();
        teamVerifyDTO.setFromDetail(false);
        teamVerifyDTO.setIsNew(isNew);
        teamVerifyDTO.setDataId(Collections.singletonList(validateDataDTO.getDataId()));
        teamVerifyDTO.setCreatorId(creatorId);
        if (Objects.nonNull(validateDataDTO.getFromApproval())) {
            //兼容一下联合审批的场景下，如果上游业务都不需要校验团队权限，那么下游业务也不应该校验团队权限
            teamVerifyDTO.setFromApproval(validateDataDTO.getFromApproval());
        }else {
            teamVerifyDTO.setFromApproval(Objects.nonNull(validateDataDTO.getTaskId()));
        }
        teamVerifyDTO.setFromCover(Objects.equals(validateDataDTO.getIsCover(), BasicConstant.ONE));
        List<ReturnUserAndDepartmentPojo> ownerList = validateDataDTO.getOwnerIds();
        List<ReturnUserAndDepartmentPojo> coUserList = validateDataDTO.getCoUserId();
        Set<String> ownerIdList = new HashSet<>();
        Set<String> coUserIdList = new HashSet<>();
        if (CollectionsUtil.isNotEmpty(ownerList)) {
            ownerList.forEach(owner -> ownerIdList.add(Objects.toString(owner.getId(), "")));
        }
        if (CollectionsUtil.isNotEmpty(coUserList)) {
            coUserList.forEach(coUser -> coUserIdList.add(Objects.toString(coUser.getId(), "")));
        }
        //paas表单有个特殊业务场景就是，如果ownerIdList为空，就用创建人id作为负责人id
        if (Objects.equals(SaasMarkEnum.PAAS.getCode(), saasMark) && CollectionsUtil.isEmpty(ownerIdList)) {
            TeamFieldExplainPOJO teamFieldExplainPOJO = proFormHelp.getTeamFieldExplain(validateDataDTO.getCorpid(), validateDataDTO.getFormId(), validateDataDTO.getBusinessType());
            FieldAttrEntity ownerField = teamFieldExplainPOJO.getOwnerField();
            if (Objects.isNull(ownerField) || isNew) {
                //这里的判断主要是为了解决工作流那边的，一定要有负责人字段的值，不然会把负责人删除掉。
                ownerIdList.add(creatorId);
            }
        }
        teamVerifyDTO.setNewAddMainUserList(ownerIdList);
        teamVerifyDTO.setNewAddCoUserList(coUserIdList);
//        TeamAfterVerifyDTO teamAfterVerifyDTO = teamStrategy.verify(teamVerifyDTO);
        TeamAfterVerifyDTO teamAfterVerifyDTO = verifyFromForm(teamVerifyDTO);
        SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo = validateDataDTO.getSaasNeedRedundantAttrPoJo() == null ?
                new SaasNeedRedundantAttrPojo() : validateDataDTO.getSaasNeedRedundantAttrPoJo();
        saasNeedRedundantAttrPojo.setTeamAfterVerifyDTO(teamAfterVerifyDTO);
        validateDataDTO.setSaasNeedRedundantAttrPoJo(saasNeedRedundantAttrPojo);

        List<TeamBatchPojo> teamBatchPojos = teamAfterVerifyDTO.getTeamBatchPojos();
        if (CollectionsUtil.isNotEmpty(teamBatchPojos)) {
            throw new XbbException(teamBatchPojos.get(0).getCode(), teamBatchPojos.get(0).getFailMsgReason());
        }
    }

    @Override
    public List<TeamBatchPojo> save(TeamVerifyDTO teamVerifyDTO) throws XbbException {
        Integer businessType = teamVerifyDTO.getBusinessType();
        TeamAfterVerifyDTO teamAfterVerifyDTO = new TeamAfterVerifyDTO();
        try {
            // 封装校验
            teamAfterVerifyDTO = verify(teamVerifyDTO);

            businessSave(teamAfterVerifyDTO);

            // api回调处理
            apiCallBack(teamVerifyDTO.getDataId(), businessType, teamVerifyDTO.getCorpid());
        } catch (Exception e) {
            LOG.info("非业务逻辑层的保存团队报错:{}", e);
            throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_271004.getCode(), UserTeamErrorCodeEnum.API_ERROR_271004.getMsg());
        } finally {
            List<TeamBatchPojo> teamBatchPojos = teamAfterVerifyDTO.getTeamBatchPojos();
            if (!Objects.equals(teamVerifyDTO.getBatchTag(), BasicConstant.ONE) && CollectionsUtil.isNotEmpty(teamBatchPojos)) {
                throw new XbbException(teamBatchPojos.get(0).getCode(), teamBatchPojos.get(0).getFailMsgReason());
            }
            if (CollectionsUtil.isNotEmpty(teamAfterVerifyDTO.getTeamBatchPojos())) {
                return teamAfterVerifyDTO.getTeamBatchPojos();
            } else {
                return new ArrayList<>();
            }
        }
    }


    /**
     * Description: 团队修改日志/消息推送
     * @param teamAfterVerifyDTO
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2022/1/7 14:55
     * @since
     */
    @Override
    public void log(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException{
        Runnable runnable = () -> {
            try {
                Integer batchTag = teamAfterVerifyDTO.getBatchTag();
                Map<String, Set<String>> addMainUserMap = teamAfterVerifyDTO.getAddMainUserMap();
                Map<String, Set<String>> addCoUserMap = teamAfterVerifyDTO.getAddCoUserMap();
                Map<String, Set<String>> delMainUserMap = teamAfterVerifyDTO.getDelMainUserMap();
                Map<String, Set<String>> delCoUserMap = teamAfterVerifyDTO.getDelCoUserMap();
                Map<String, Set<String>> updateToMainUserMap = teamAfterVerifyDTO.getUpdateToMainUserMap();
                Map<String, Set<String>> updateToCoUserMap = teamAfterVerifyDTO.getUpdateToCoUserMap();
                String operatorName = teamAfterVerifyDTO.getLoginUser().getName();
                String operatorId = teamAfterVerifyDTO.getLoginUser().getUserId();
                String corpId = teamAfterVerifyDTO.getCorpid();
                Long formId = teamAfterVerifyDTO.getFormId();
                Integer operateTag = teamAfterVerifyDTO.getOperateTag();
                Integer model = teamAfterVerifyDTO.getFormTeamSetEntity().getModel();
                Integer businessType = teamAfterVerifyDTO.getBusinessType();
                //查询一下表单信息
                String formName = null;
                PaasFormEntityExt paasFormEntityExt = null;
                if (Objects.equals(teamAfterVerifyDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
                    WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(formId, teamAfterVerifyDTO.getCorpid());
                    formName = workOrderFormEntityExt.getName();
                } else {
                    paasFormEntityExt = paasFormModel.getByKey(formId, corpId);
                    formName = paasFormEntityExt.getName();
                }
                //业务详情界面的时候会传进来的参数
                Map<Long, PaasFormDataEntity> paasFormDataEntityExtMap = teamAfterVerifyDTO.getPaasFormDataEntityExtMap();

                List<Long> dataIdIn = teamAfterVerifyDTO.getDataId();
                TeamSaveMiddlePojo teamSaveMiddlePojo = teamAfterVerifyDTO.getTeamSaveMiddlePojo();

                //消息推送
                for (Long dataId : dataIdIn) {
                    if (Objects.nonNull(teamSaveMiddlePojo) && Objects.nonNull(teamSaveMiddlePojo.getPaymentSheetSonDataIdList()) &&
                            teamSaveMiddlePojo.getPaymentSheetSonDataIdList().contains(dataId)) {
                        //这边主要是回款单的特殊逻辑
                        continue;
                    }
                    Set<String> addMainUserList = Objects.isNull(addMainUserMap) ? null : addMainUserMap.get(String.valueOf(dataId));
                    Set<String> addCoUserList = Objects.isNull(addCoUserMap) ? null : addCoUserMap.get(String.valueOf(dataId));
                    Set<String> delMainUserList = Objects.isNull(delMainUserMap) ? null : delMainUserMap.get(String.valueOf(dataId));
                    Set<String> delCoUserList = Objects.isNull(delCoUserMap) ? null : delCoUserMap.get(String.valueOf(dataId));
                    Set<String> updateToCoUserList = Objects.isNull(updateToCoUserMap) ? null : updateToCoUserMap.get(String.valueOf(dataId));
                    Set<String> updateToMainUserList = Objects.isNull(updateToMainUserMap) ? null : updateToMainUserMap.get(String.valueOf(dataId));
                    //这个主要是新增主业务的时候会传的参数
                    PaasFormDataEntity paasFormDataEntity = teamAfterVerifyDTO.getPaasFormDataEntity();
                    if (Objects.isNull(paasFormDataEntity)) {
                        paasFormDataEntity = paasFormDataEntityExtMap.get(dataId);
                    }
                    paasFormDataEntity = entityTransfer(paasFormDataEntity, businessType);
                    String saveName = getSaveName(corpId, teamAfterVerifyDTO.getBusinessType(), paasFormEntityExt, paasFormDataEntity);
                    String httpHeader = teamAfterVerifyDTO.getHttpHeader();
                    if(Objects.equals(operateTag, UserTeamOperateTagEnum.HANDOVER.getOperateTag())){
                        //移交-》需要区分隔离模式和共享模式; 原负责人信息存在delMainUserList
                        // 隔离模式：替换后的负责人信息存在addMainUserList
                        // 共享模式：替换后的负责人信息可能存在updateToMainUserList、addMainUserList
                        if (CollectionUtils.isEmpty(delMainUserList)) {
                            continue;
                        }
                        String originUserId = delMainUserList.stream().findFirst().get();
                        String changeUserId = null;
                        if (Objects.equals(model, FormPatternEnum.FORM_ISOLATION.getModel())) {
                            changeUserId = addMainUserList.stream().findFirst().get();
                        } else {
                            if (CollectionsUtil.isNotEmpty(updateToMainUserList)) {
                                changeUserId = updateToMainUserList.stream().findFirst().get();
                            } else {
                                changeUserId = addMainUserList.stream().findFirst().get();
                            }
                        }
                        //移交操作的时候需要判断如果是客户或者线索的业务则需要进行消息推送
                        if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType)
                                || Objects.equals(XbbRefTypeEnum.CLUE.getCode(), businessType)) {
                            //推送+移交
                            changeMainPush(teamAfterVerifyDTO, saveName, paasFormDataEntity, originUserId, changeUserId);
                        }
                    }else{
                        if (CollectionsUtil.isNotEmpty(addMainUserList)) {
                            //推送
                            addUserPush(teamAfterVerifyDTO, true, saveName, addMainUserList, paasFormDataEntity);
                        }

                        //新增协同人
                        if (addCoUserList != null && !addCoUserList.isEmpty()) {
                            //推送
                            addUserPush(teamAfterVerifyDTO, false, saveName, addCoUserList, paasFormDataEntity);
                        }

                        //删除负责人
                        if (CollectionsUtil.isNotEmpty(delMainUserList)) {
                            delUserPush(teamAfterVerifyDTO, true, saveName, delMainUserList, paasFormDataEntity);
                        }

                        //删除协同人
                        if (delCoUserList != null && !delCoUserList.isEmpty()) {
                            //推送
                            delUserPush(teamAfterVerifyDTO, false, saveName, delCoUserList, paasFormDataEntity);
                        }
                    }
                }

                //日志
                if(Objects.nonNull(batchTag)&&Objects.equals(1,batchTag)){
                    // 批量日志
                    teamBatchLog(teamAfterVerifyDTO);
                }else {
                    //非批量的操作日志
                    for (Long dataId : dataIdIn) {
                        if (Objects.nonNull(teamSaveMiddlePojo) && Objects.nonNull(teamSaveMiddlePojo.getPaymentSheetSonDataIdList()) &&
                                teamSaveMiddlePojo.getPaymentSheetSonDataIdList().contains(dataId)) {
                            //这边主要是回款单的特殊逻辑
                            continue;
                        }
                        //这个主要是新增主业务的时候会传的参数
                        PaasFormDataEntity paasFormDataEntity = teamAfterVerifyDTO.getPaasFormDataEntity();
                        if (Objects.isNull(paasFormDataEntity)) {
                            paasFormDataEntity = paasFormDataEntityExtMap.get(dataId);
                        }
                        paasFormDataEntity = entityTransfer(paasFormDataEntity, businessType);
                        Set<String> addMainUserList = Objects.isNull(addMainUserMap) ? null : addMainUserMap.get(String.valueOf(dataId));
                        Set<String> addCoUserList = Objects.isNull(addCoUserMap) ? null : addCoUserMap.get(String.valueOf(dataId));
                        Set<String> delMainUserList = Objects.isNull(delMainUserMap) ? null : delMainUserMap.get(String.valueOf(dataId));
                        Set<String> delCoUserList = Objects.isNull(delCoUserMap) ? null : delCoUserMap.get(String.valueOf(dataId));
                        Set<String> updateToCoUserList = Objects.isNull(updateToCoUserMap) ? null : updateToCoUserMap.get(String.valueOf(dataId));
                        Set<String> updateToMainUserList = Objects.isNull(updateToMainUserMap) ? null : updateToMainUserMap.get(String.valueOf(dataId));

                        String saveName = getSaveName(corpId, teamAfterVerifyDTO.getBusinessType(), paasFormEntityExt, paasFormDataEntity);
                        String httpHeader = teamAfterVerifyDTO.getHttpHeader();
                        //新增负责人和新增团队和移交负责人都有addMainUserList,所以下面需要两层区分：（1）第一层根据addMainUserList区分（2）第二层根据operateTag去区分
                        if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_TEAM_TAG.getOperateTag())) {
                            int flag = 0;
                            teamLog(addMainUserList, operatorId, corpId, operatorName, formName, saveName, true, flag, operateTag, httpHeader, null, null, null);
                        } else if (Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_TEAM_TAG.getOperateTag())) {
                            int flag = 1;
                            teamLog(delMainUserList, operatorId, corpId, operatorName, formName, saveName, true, flag, operateTag, httpHeader, null, null, null);
                        } else if (Objects.equals(operateTag, UserTeamOperateTagEnum.HANDOVER.getOperateTag())) {
                            //移交-》需要区分隔离模式和共享模式; 原负责人信息存在delMainUserList
                            // 隔离模式：替换后的负责人信息存在addMainUserList
                            // 共享模式：替换后的负责人信息可能存在updateToMainUserList、addMainUserList
                            int flag = 3;
                            if (CollectionUtils.isEmpty(delMainUserList)) {
                                continue;
                            }
                            String originUserId = delMainUserList.stream().findFirst().get();
                            String changeUserId = null;
                            if (Objects.equals(model, FormPatternEnum.FORM_ISOLATION.getModel())) {
                                changeUserId = addMainUserList.stream().findFirst().get();
                            } else {
                                if (CollectionsUtil.isNotEmpty(updateToMainUserList)) {
                                    changeUserId = updateToMainUserList.stream().findFirst().get();
                                } else {
                                    changeUserId = addMainUserList.stream().findFirst().get();
                                }
                            }
                            //如果是移交给团队内的协同人，则addMainUserList为null，补丁一下
                            if (CollectionUtils.isNotEmpty(updateToMainUserMap.get(String.valueOf(dataId)))) {
                                teamLog(updateToMainUserMap.get(String.valueOf(dataId)), operatorId, corpId, operatorName, formName, saveName, true, flag, operateTag, httpHeader, originUserId, changeUserId, model);
                            } else {
                                teamLog(addMainUserList, operatorId, corpId, operatorName, formName, saveName, true, flag, operateTag, httpHeader, originUserId, changeUserId, model);
                            }

                        } else {
                            if (CollectionsUtil.isNotEmpty(addMainUserList)) {
                                int flag = 0;
                                operateTag = UserTeamOperateTagEnum.ADD_MAIN.getOperateTag();
                                teamLog(addMainUserList, operatorId, corpId, operatorName, formName, saveName, true, flag, operateTag, httpHeader, null, null, null);
                            }

                            //新增协同人
                            if (addCoUserList != null && !addCoUserList.isEmpty()) {
                                //日志操作flag:0为新增,1为删除,2为修改,3移交
                                int flag = 0;
                                operateTag = UserTeamOperateTagEnum.ADD_COUSER.getOperateTag();
                                teamLog(addCoUserList, operatorId, corpId, operatorName, formName, saveName, false, flag, operateTag, httpHeader, null, null, null);
                            }

                            //删除负责人
                            if (CollectionsUtil.isNotEmpty(delMainUserList)) {
                                //日志操作flag:0为新增,1为删除,2为修改,3移交
                                int flag = 1;
                                operateTag = UserTeamOperateTagEnum.DEL_MAIN.getOperateTag();
                                teamLog(delMainUserList, operatorId, corpId, operatorName, formName, saveName, true, flag, operateTag, httpHeader, null, null, null);
                            }

                            //删除协同人
                            if (delCoUserList != null && !delCoUserList.isEmpty()) {
                                //日志操作flag:0为新增,1为删除,2为修改,3移交
                                int flag = 1;
                                operateTag = UserTeamOperateTagEnum.DEL_COUSER.getOperateTag();
                                teamLog(delCoUserList, operatorId, corpId, operatorName, formName, saveName, false, flag, operateTag, httpHeader, null, null, null);
                            }

                            //负责人变更(将负责人变成协同人)，记录日志是按照新增协同人日志去操作的
                            if (updateToCoUserList != null && !updateToCoUserList.isEmpty()) {
                                //日志操作flag:0为新增,1为删除,2为修改,3移交
                                int flag = 2;
                                operateTag = UserTeamOperateTagEnum.ADD_COUSER.getOperateTag();
                                teamLog(updateToCoUserList, operatorId, corpId, operatorName, formName, saveName, true, flag, operateTag, httpHeader, null, null, null);
                                //变更操作暂不推送
                            }

                            //协同人变更（将协同人变成负责人）,记录日志按照新增负责人日志去操作
                            if (updateToMainUserList != null && !updateToMainUserList.isEmpty()) {
                                //日志操作flag:0为新增,1为删除,2为修改,3移交
                                int flag = 2;
                                operateTag = UserTeamOperateTagEnum.ADD_MAIN.getOperateTag();
                                teamLog(updateToMainUserList, operatorId, corpId, operatorName, formName, saveName, false, flag, operateTag, httpHeader, null, null, null);
                                //变更操作暂不推送
                            }
                        }

                    }
                }
            } catch (Exception e) {
                LOG.warn("com.xbongbong.paas.service.team.strategy.AbstractTeamStrategy.log,{}, operateTag {}, isImport {}, fromBackPublic {}, isBack {}, dataIds {}, isNew {}, isInheritance {}, corpid {}, businessType {}", ProBaseConfig.getProjectName(), teamAfterVerifyDTO.getOperateTag(), teamAfterVerifyDTO.getIsImport(), teamAfterVerifyDTO.getFromBackPublic(), teamAfterVerifyDTO.getIsBack(), JSON.toJSONString(teamAfterVerifyDTO.getDataId()), teamAfterVerifyDTO.getIsNew(), teamAfterVerifyDTO.getIsInheritance(), teamAfterVerifyDTO.getCorpid(), teamAfterVerifyDTO.getBusinessType());
            }
        };
        logThreadPoolBeanConfig.sysLogThreadPool().execute(runnable);
    }
    /**
     *
     * @Description: 删除负责人/协同人推送
     * @param teamAfterVerifyDTO
     * @param isMain
     * @param saveName
     * @param delUserSet 需要删除的用户
     * @param paasFormDataEntity
     * @return: void
     * @Author: shen.yang
     * @Date: 2022/1/12  19:52
     */
    protected void delUserPush(TeamAfterVerifyDTO teamAfterVerifyDTO, boolean isMain,  String saveName, Set<String> delUserSet, PaasFormDataEntity paasFormDataEntity) throws XbbException {

    }
    /**
     *
     * @Description: 团队添加负责人/协同人推送
     * @param teamAfterVerifyDTO
     * @param isMain
     * @param saveName
     * @param addUserSet 新增负责人/新增协同人需要推送的人
     * @param paasFormDataEntity
     * @return: void
     * @Author: shen.yang
     * @Date: 2022/1/12  19:18
     */
    protected void addUserPush(TeamAfterVerifyDTO teamAfterVerifyDTO, boolean isMain, String saveName, Set<String> addUserSet, PaasFormDataEntity paasFormDataEntity) throws XbbException {

    }

    protected void changeMainPush(TeamAfterVerifyDTO teamAfterVerifyDTO, String saveName, PaasFormDataEntity paasFormDataEntity, String originUserId, String changeUserId) throws XbbException {

    }


    /**
     * 批量操作日志
     * date: 2022/6/20 11:07 上午
     * @Author yingjf
     * @param teamAfterVerifyDTO:
     */
    private void teamBatchLog(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException{
        Map<String, Set<String>> addMainUserMap = teamAfterVerifyDTO.getAddMainUserMap();
        Map<String, Set<String>> addCoUserMap = teamAfterVerifyDTO.getAddCoUserMap();
        Map<String, Set<String>> delMainUserMap = teamAfterVerifyDTO.getDelMainUserMap();
        Map<String, Set<String>> delCoUserMap = teamAfterVerifyDTO.getDelCoUserMap();
        Map<String, Set<String>> updateToMainUserMap = teamAfterVerifyDTO.getUpdateToMainUserMap();
        Map<String, Set<String>> updateToCoUserMap = teamAfterVerifyDTO.getUpdateToCoUserMap();
        String operatorName = teamAfterVerifyDTO.getLoginUser().getName();
        String operatorId = teamAfterVerifyDTO.getLoginUser().getUserId();
        String corpId = teamAfterVerifyDTO.getCorpid();
        Long formId = teamAfterVerifyDTO.getFormId();
        Integer operateTag = teamAfterVerifyDTO.getOperateTag();
        Integer model = teamAfterVerifyDTO.getFormTeamSetEntity().getModel();
        Integer businessType = teamAfterVerifyDTO.getBusinessType();
        //查询一下表单信息
        String formName = null;
        PaasFormEntityExt paasFormEntityExt = null;
        if (Objects.equals(teamAfterVerifyDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
            WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(formId, teamAfterVerifyDTO.getCorpid());
            formName = workOrderFormEntityExt.getName();
        }else {
            paasFormEntityExt = paasFormModel.getByKey(formId, corpId);
            formName = paasFormEntityExt.getName();
        }
        //业务详情界面的时候会传进来的参数
        Map<Long, PaasFormDataEntity> paasFormDataEntityExtMap = teamAfterVerifyDTO.getPaasFormDataEntityExtMap();

        List<Long> dataIdIn = teamAfterVerifyDTO.getDataId();
        int size = dataIdIn.size();
        TeamSaveMiddlePojo teamSaveMiddlePojo = teamAfterVerifyDTO.getTeamSaveMiddlePojo();
        Long dataId  = dataIdIn.get(0);
        // 批量的日志
        if (Objects.nonNull(teamSaveMiddlePojo) && Objects.nonNull(teamSaveMiddlePojo.getPaymentSheetSonDataIdList()) &&
                teamSaveMiddlePojo.getPaymentSheetSonDataIdList().contains(dataId)) {
            //这边主要是回款单的特殊逻辑
        }
        //这个主要是新增主业务的时候会传的参数
        PaasFormDataEntity paasFormDataEntity = teamAfterVerifyDTO.getPaasFormDataEntity();
        String saveName = null;
        Set<String> addMainUserList = Objects.isNull(addMainUserMap) ? null : addMainUserMap.get(addMainUserMap.keySet().toArray(new String[1])[0]);
        Set<String> addCoUserList = Objects.isNull(addCoUserMap) ? null : addCoUserMap.get(addCoUserMap.keySet().toArray(new String[1])[0]);
        Set<String> delMainUserList = Objects.isNull(delMainUserMap) ? null : delMainUserMap.get(delMainUserMap.keySet().toArray(new String[1])[0]);
        Set<String> delCoUserList = Objects.isNull(delCoUserMap) ? null : delCoUserMap.get(delCoUserMap.keySet().toArray(new String[1])[0]);
        Set<String> updateToCoUserList = Objects.isNull(updateToCoUserMap) ? null : updateToCoUserMap.get(updateToCoUserMap.keySet().toArray(new String[1])[0]);
        Set<String> updateToMainUserList = Objects.isNull(updateToMainUserMap) ? null : updateToMainUserMap.get(updateToMainUserMap.keySet().toArray(new String[1])[0]);

        String httpHeader = teamAfterVerifyDTO.getHttpHeader();
        //新增负责人和新增团队和移交负责人都有addMainUserList,所以下面需要两层区分：（1）第一层根据addMainUserList区分（2）第二层根据operateTag去区分
        if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_TEAM_TAG.getOperateTag())) {
            int flag = 0;
            saveName = packageSaveName( corpId, businessType, paasFormDataEntity, paasFormDataEntityExtMap,paasFormEntityExt,addMainUserMap);
            teamBatchLog(addMainUserMap.size(),addMainUserList,operatorId,corpId,operatorName,formName,saveName, true,flag,operateTag,httpHeader,null,null, null);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_TEAM_TAG.getOperateTag())) {
            int flag = 1;
            saveName = packageSaveName( corpId, businessType, paasFormDataEntity, paasFormDataEntityExtMap,paasFormEntityExt,
                    delMainUserMap);
            teamBatchLog(delMainUserMap.size(),delMainUserList,operatorId,corpId,operatorName,formName,saveName, true,flag,operateTag,httpHeader, null, null, null);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.HANDOVER.getOperateTag())) {
            //移交-》需要区分隔离模式和共享模式; 原负责人信息存在delMainUserList
            // 隔离模式：替换后的负责人信息存在addMainUserList
            // 共享模式：替换后的负责人信息可能存在updateToMainUserList、addMainUserList
            int flag = 3;
            String originUserId = delMainUserList.stream().findFirst().get();
            String changeUserId = null;
            if (Objects.equals(model, FormPatternEnum.FORM_ISOLATION.getModel())) {
                changeUserId = addMainUserList.stream().findFirst().get();
            }else {
                if (CollectionsUtil.isNotEmpty(updateToMainUserList)) {
                    changeUserId = updateToMainUserList.stream().findFirst().get();
                }else {
                    changeUserId = addMainUserList.stream().findFirst().get();
                }
            }
            //如果是移交给团队内的协同人，则addMainUserList为null，补丁一下
            if(CollectionUtils.isNotEmpty(updateToMainUserMap.get(String.valueOf(dataId)))){
                saveName = packageSaveName( corpId, businessType, paasFormDataEntity, paasFormDataEntityExtMap,paasFormEntityExt,
                        updateToMainUserMap);
                teamBatchLog(updateToMainUserMap.size(),updateToMainUserMap.get(String.valueOf(dataId)),operatorId,corpId,operatorName,formName,saveName, true,flag,operateTag,httpHeader, originUserId, changeUserId, model);
            }else{
                saveName = packageSaveName( corpId, businessType, paasFormDataEntity, paasFormDataEntityExtMap,paasFormEntityExt,
                        addMainUserMap);
                teamBatchLog(addMainUserMap.size(),addMainUserList,operatorId,corpId,operatorName,formName,saveName, true,flag,operateTag,httpHeader, originUserId, changeUserId, model);
            }
        }else {
            if (CollectionsUtil.isNotEmpty(addMainUserList)) {
                int flag = 0;
                operateTag = UserTeamOperateTagEnum.ADD_MAIN.getOperateTag();
                saveName = packageSaveName( corpId, businessType, paasFormDataEntity, paasFormDataEntityExtMap,paasFormEntityExt,
                        addMainUserMap);
                teamBatchLog(addMainUserMap.size(),addMainUserList,operatorId,corpId,operatorName,formName,saveName, true,flag,operateTag,httpHeader, null, null, null);
            }

            //新增协同人
            if(addCoUserList != null && !addCoUserList.isEmpty()){
                //日志操作flag:0为新增,1为删除,2为修改,3移交
                int flag = 0;
                operateTag = UserTeamOperateTagEnum.ADD_COUSER.getOperateTag();
                saveName = packageSaveName( corpId, businessType, paasFormDataEntity, paasFormDataEntityExtMap,paasFormEntityExt,
                        addCoUserMap);
                teamBatchLog(addCoUserMap.size(),addCoUserList,operatorId,corpId,operatorName,formName,saveName,false,flag,operateTag,httpHeader,null,null,null);
            }

            //删除负责人
            if (CollectionsUtil.isNotEmpty(delMainUserList)) {
                //日志操作flag:0为新增,1为删除,2为修改,3移交
                int flag = 1;
                operateTag = UserTeamOperateTagEnum.DEL_MAIN.getOperateTag();
                saveName = packageSaveName( corpId, businessType, paasFormDataEntity, paasFormDataEntityExtMap,paasFormEntityExt,
                        delMainUserMap);
                teamBatchLog(delMainUserMap.size(),delMainUserList,operatorId,corpId,operatorName,formName,saveName, true,flag,operateTag,httpHeader,null,null,null);
            }

            //删除协同人
            if(delCoUserList != null && !delCoUserList.isEmpty()){
                //日志操作flag:0为新增,1为删除,2为修改,3移交
                int flag = 1;
                operateTag = UserTeamOperateTagEnum.DEL_COUSER.getOperateTag();
                saveName = packageSaveName( corpId, businessType, paasFormDataEntity, paasFormDataEntityExtMap,paasFormEntityExt,
                        delCoUserMap);
                teamBatchLog(delCoUserMap.size(),delCoUserList,operatorId,corpId,operatorName,formName,saveName, false,flag,operateTag,httpHeader,null,null,null);
            }

            //负责人变更(将负责人变成协同人)，记录日志是按照新增协同人日志去操作的
            if(updateToCoUserList != null && !updateToCoUserList.isEmpty()){
                //日志操作flag:0为新增,1为删除,2为修改,3移交
                int flag = 2;
                operateTag = UserTeamOperateTagEnum.ADD_COUSER.getOperateTag();
                saveName = packageSaveName( corpId, businessType, paasFormDataEntity, paasFormDataEntityExtMap,paasFormEntityExt,
                        updateToCoUserMap);
                teamBatchLog(updateToCoUserMap.size(),updateToCoUserList,operatorId,corpId,operatorName,formName,saveName, true,flag,operateTag,httpHeader,null,null,null);
            }
            //协同人变更（将协同人变成负责人）,记录日志按照新增负责人日志去操作
            if(updateToMainUserList != null && !updateToMainUserList.isEmpty()){
                //日志操作flag:0为新增,1为删除,2为修改,3移交
                int flag = 2;
                operateTag = UserTeamOperateTagEnum.ADD_MAIN.getOperateTag();
                saveName = packageSaveName( corpId, businessType, paasFormDataEntity, paasFormDataEntityExtMap,paasFormEntityExt,
                        updateToMainUserMap);
                teamBatchLog(updateToMainUserMap.size(),updateToMainUserList,operatorId,corpId,operatorName,formName,saveName, false,flag,operateTag,httpHeader,null,null,null);
            }
        }
    }


    private String packageSaveName(String corpId,Integer businessType,PaasFormDataEntity paasFormDataEntity,Map<Long, PaasFormDataEntity> paasFormDataEntityExtMap
            ,PaasFormEntityExt paasFormEntityExt,Map<String, Set<String>> map) throws XbbException {
        String saveName = "";
        if (Objects.isNull(paasFormDataEntity)) {
            //Set<Long> ids = paasFormDataEntityExtMap.keySet();
            List<String> nameList = new ArrayList<>();
            for(String id:map.keySet()){
                paasFormDataEntity = paasFormDataEntityExtMap.get(Long.parseLong(id));
                paasFormDataEntity = entityTransfer(paasFormDataEntity, businessType);
                saveName = getSaveName(corpId, businessType, paasFormEntityExt, paasFormDataEntity);
                nameList.add(saveName);
            }
            saveName = StringUtils.join(nameList, "、");
        }
        return saveName;
    }
    /**
     *
     * date: 2022/5/10 3:04 下午
     * @Author yingjf
     */
    private void teamBatchLog(int size,Set<String> userList, String operatorId , String corpId, String operatorName, String xbbRefTypeName, String saveName, boolean isMain,
                              int flag, Integer operateTag, String httpHeader, String originUserId, String changeUserId, Integer model){
        if(CollectionsUtil.isEmpty(userList)){
            // 全部失败的情况不加日志
            return;
        }
        String opObjectName = operatorName;
        OperateTypeEnum operateTypeEnum = null;
        String isMainStr = null;
        String memo = null;
        String message = null;
        //所属模板封装
        //关键词封装
        if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_MAIN.getOperateTag())) {
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.MAIN_USER_ALIAS);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_COUSER.getOperateTag())) {
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.CO_USER_ALIAS);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_TEAM_TAG.getOperateTag())) {
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.TEAM_ALIAS);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_TEAM_TAG.getOperateTag())) {
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.TEAM_ALIAS);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.HANDOVER.getOperateTag())) {
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.MAIN_USER_ALIAS);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_MAIN.getOperateTag())) {
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.MAIN_USER_ALIAS);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_COUSER.getOperateTag())) {
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.CO_USER_ALIAS);
        }

        //所属操作封装
        if (flag == 0) {
            operateTypeEnum = OperateTypeEnum.NEW;
        }else if (flag == 1) {
            operateTypeEnum = OperateTypeEnum.DELETE;
        }else if (flag == 2) {
            operateTypeEnum = OperateTypeEnum.EDIT;
        }else if (flag == 3) {
            operateTypeEnum = OperateTypeEnum.HANDOVER;
        }
        //查询用户相关信息、操作对象
        List<UserEntity> userEntityList = null;
        String userNameListStr = null;
        String operateObjectName = null;
        String afterOwnName = null;
        if (Objects.equals(operateTag, UserTeamOperateTagEnum.HANDOVER.getOperateTag())) {
            userEntityList = userModel.getByUserIdIn(corpId,Arrays.asList(originUserId, changeUserId),false);
            for (UserEntity userEntity : userEntityList) {
                if (Objects.equals(userEntity.getUserId(), changeUserId)) {
                    operateObjectName = userEntity.getName();
                }else {
                    afterOwnName = userEntity.getName();;
                }
            }
        }else {
            userEntityList = userModel.getByUserIdIn(corpId,CollectionUtils.isNotEmpty(userList) ? new ArrayList<>(userList) : new ArrayList<>(),false);
            List<String> userNameList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            userEntityList.forEach(user -> userNameList.add(user.getName()));
            userNameListStr = StringUtils.join(userNameList, "、");
            if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_TEAM_TAG.getOperateTag()) ||
                    Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_TEAM_TAG.getOperateTag())) {
                operateObjectName = StringUtils.join(userNameList, "、") + I18nMessageUtil.getMessage(TeamMembersConstant.TEAM_SUFFIX);;
            }else {
                operateObjectName = StringUtils.join(userNameList, "、");
            }
        }

        //下面对message进行封装
        if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_MAIN.getOperateTag()) ||
                Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_COUSER.getOperateTag())) {
//           用户“%s”给%s批量新增了%s，合计：%s条数据操作成功
            message = I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_ADD_MAIN_USER_NEW);
            memo = String.format(message, operatorName, xbbRefTypeName,isMainStr,userNameListStr, size);
            opObjectName = userNameListStr;
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_MAIN.getOperateTag()) ||
                Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_COUSER.getOperateTag())) {
            //用户“%s”批量删除了%s的%s“%s”，合计：%s条数据操作成功
            message = I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_DEL_MAIN_USER_NEW);
            memo = String.format(message, operatorName, xbbRefTypeName,isMainStr, userNameListStr,size);
            opObjectName = userNameListStr;
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.UPDATE_MAIN.getOperateTag()) ||
                Objects.equals(operateTag, UserTeamOperateTagEnum.UPDATE_COUSER.getOperateTag())) {
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_TEAM_TAG.getOperateTag())) {
            //用户“%s”批量创建了%s下“%s”的负责团队，合计：%s条数据操作成功
            message = I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_ADD_TEAM);
            memo = String.format(message, operatorName, xbbRefTypeName,userNameListStr,size);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_TEAM_TAG.getOperateTag())) {
            //用户“%s”批量解散了%s下“%s”的负责团队，合计：%s条数据操作成功
            message = I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_DEL_TEAM);
            memo = String.format(message, operatorName, xbbRefTypeName,userNameListStr,size);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.HANDOVER.getOperateTag()) && Objects.equals(model, FormPatternEnum.FORM_ISOLATION.getModel())) {
            //用户“%s”批量移交了%s下“%s”的团队负责人为“%s”，合计 %s操作成功
            message = I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_HANDOVER_NEW);
            memo = String.format(message, operatorName, xbbRefTypeName,afterOwnName,operateObjectName,size);
            opObjectName = operateObjectName;
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.HANDOVER.getOperateTag()) && Objects.equals(model, FormPatternEnum.FORM_SHARE.getModel())) {
            //用户“%s”批量把“%s”负责的“%s”移交给“%s”，合计： %s 条数据移交成功，具体操作数据见详情
            message = I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_HANDOVER_NEW);
            memo = String.format(message, operatorName, xbbRefTypeName,afterOwnName,operateObjectName,size);
            opObjectName = operateObjectName;
        }
        try{
            List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            InfoArrPojo infoArrPojo = new InfoArrPojo();
            infoArrPojo.setTitle(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_OPERATION_OBJECT));
            infoArrPojo.setContent(saveName);
            infoArrPojoList.add(infoArrPojo);
            mongoLogHelp.buildLog4InfoArrWithoutAsync(infoArrPojoList, corpId,operatorId.toString(), operatorName, OperateModuleTypeEnum.RESPONSIBLE_TEAM, operateTypeEnum,
                    "", opObjectName, memo, httpHeader);

        }catch (XbbException e){
            LOG.error("com.xbongbong.paas.service.team.strategy.AbstractTeamStrategy.teamBatchLog error", e);
        }
    }

    /**
     *
     * @Description: 团队成员操作日志公共方法
     * @param userList
     * @param operatorId
     * @param corpId
     * @param operatorName
     * @param xbbRefTypeName
     * @param saveName
     * @param isMain
     * @param flag
     * @param operateTag 操作标识
     * @param httpHeader
     * @param originUserId 需要被替换的负责人userId
     * @param changeUserId 需要替换成的负责人userId
     * @param model 当前表单模式
     * @return: void
     * @Author: shen.yang
     * @Date: 2022/1/12  15:59
     */
    private void teamLog(Set<String> userList, String operatorId , String corpId, String operatorName, String xbbRefTypeName, String saveName, boolean isMain,
                         int flag, Integer operateTag, String httpHeader, String originUserId, String changeUserId, Integer model){

        OperateTypeEnum operateTypeEnum = null;
        String isMainStr = null;
        String memo = null;
        String message = null;
        //关键词封装
        if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_MAIN.getOperateTag())) {
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.MAIN_USER_ALIAS);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_COUSER.getOperateTag())) {
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.CO_USER_ALIAS);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_TEAM_TAG.getOperateTag())) {
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.TEAM_ALIAS);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_TEAM_TAG.getOperateTag())) {
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.TEAM_ALIAS);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.HANDOVER.getOperateTag())) {
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.MAIN_USER_ALIAS);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_MAIN.getOperateTag())) {
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.MAIN_USER_ALIAS);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_COUSER.getOperateTag())) {
            isMainStr = I18nMessageUtil.getMessage(ListBatchConstant.CO_USER_ALIAS);
        }

        //所属操作封装
        if (flag == 0) {
            operateTypeEnum = OperateTypeEnum.NEW;
        }else if (flag == 1) {
            operateTypeEnum = OperateTypeEnum.DELETE;
        }else if (flag == 2) {
            operateTypeEnum = OperateTypeEnum.EDIT;
        }else if (flag == 3) {
            operateTypeEnum = OperateTypeEnum.HANDOVER;
        }

        //查询用户相关信息、操作对象
        List<UserEntity> userEntityList = null;
        String userNameListStr = null;
        String operateObjectName = null;
        String afterOwnName = null;
        if (Objects.equals(operateTag, UserTeamOperateTagEnum.HANDOVER.getOperateTag())) {
            userEntityList = userModel.getByUserIdIn(corpId,Arrays.asList(originUserId, changeUserId),false);
            for (UserEntity userEntity : userEntityList) {
                if (Objects.equals(userEntity.getUserId(), changeUserId)) {
                    operateObjectName = userEntity.getName();
                }else {
                    afterOwnName = userEntity.getName();;
                }
            }
        }else {
            userEntityList = userModel.getByUserIdIn(corpId,CollectionUtils.isNotEmpty(userList) ? new ArrayList<>(userList) : new ArrayList<>(),false);
            List<String> userNameList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            userEntityList.forEach(user -> userNameList.add(user.getName()));
            userNameListStr = StringUtils.join(userNameList, "、");
            if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_TEAM_TAG.getOperateTag()) ||
                    Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_TEAM_TAG.getOperateTag())) {
                operateObjectName = StringUtils.join(userNameList, "、") + I18nMessageUtil.getMessage(TeamMembersConstant.TEAM_SUFFIX);;
            }else {
                operateObjectName = StringUtils.join(userNameList, "、");
            }
        }

        //下面对message进行封装
        if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_MAIN.getOperateTag()) ||
                Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_COUSER.getOperateTag())) {
            message = I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_MAIN_USER);
            memo = String.format(message, operatorName, xbbRefTypeName, saveName, isMainStr, userNameListStr);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_MAIN.getOperateTag()) ||
                Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_COUSER.getOperateTag())) {
            message = I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DEL_MAIN_USER);
            memo = String.format(message, operatorName, xbbRefTypeName, saveName, isMainStr, userNameListStr);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.UPDATE_MAIN.getOperateTag()) ||
                Objects.equals(operateTag, UserTeamOperateTagEnum.UPDATE_COUSER.getOperateTag())) {
            message = I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_MAIN_USER);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.ADD_TEAM_TAG.getOperateTag())) {
            message = I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_TEAM);
            memo = String.format(message, operatorName, xbbRefTypeName, saveName, userNameListStr, isMainStr);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.DEL_TEAM_TAG.getOperateTag())) {
            message = I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DEL_TEAM);
            memo = String.format(message, operatorName, xbbRefTypeName, saveName, userNameListStr, isMainStr);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.HANDOVER.getOperateTag()) && Objects.equals(model, FormPatternEnum.FORM_ISOLATION.getModel())) {
            message = I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ISOLATION_HANDOVER);
            memo = String.format(message, operatorName, xbbRefTypeName, saveName, isMainStr, afterOwnName, operateObjectName);
        }else if (Objects.equals(operateTag, UserTeamOperateTagEnum.HANDOVER.getOperateTag()) && Objects.equals(model, FormPatternEnum.FORM_SHARE.getModel())) {
            message = I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_SHARE_HANDOVER);
            memo = String.format(message, operatorName, xbbRefTypeName, saveName, operateObjectName);
        }
        try{
            mongoLogHelp.buildLogWithoutAsync(corpId, operatorId, operatorName, OperateModuleTypeEnum.RESPONSIBLE_TEAM, operateTypeEnum,
                    userList.stream().findFirst().get(), operateObjectName, memo, httpHeader);
        }catch (XbbException e){
            LOG.error("com.xbongbong.paas.service.team.strategy.AbstractTeamStrategy.log log error", e);
        }
    }

    protected PaasFormDataEntity entityTransfer(PaasFormDataEntity paasFormDataEntity, Integer businessType){
        return null;
    }

    protected void apiCallBack(List<Long> dataId, Integer businessType, String corpid) {

    }
    /**
     * Description: 校验团队（新建/编辑）
     * @param teamVerifyDTO
     * @return com.xbongbong.pro.team.TeamAfterVerifyDTO
     * @throws
     * @author 魏荣杰
     * @date 2022/1/5 20:17
     * @since
     */
    public TeamAfterVerifyDTO verifyFromForm(TeamVerifyDTO teamVerifyDTO) throws XbbException {
        String corpid = teamVerifyDTO.getCorpid();
        List<Long> dataIdIn = teamVerifyDTO.getDataId();
        Long formId = teamVerifyDTO.getFormId();
        Integer saasMark = teamVerifyDTO.getSaasMark();
        Integer businessType = teamVerifyDTO.getBusinessType();
        Integer distributorMark = teamVerifyDTO.getDistributorMark();
        Integer subBusinessType = teamVerifyDTO.getSubBusinessType();
        // 需要判权的用户id
        String userId = teamVerifyDTO.getUserId();
        // 主数据创建人id
        String creatorId = teamVerifyDTO.getCreatorId();
        // 需要判权的用户/当前操作人
        UserVO loginUser = teamVerifyDTO.getLoginUser();
        // 要添加的负责人
        Set<String> newAddMainUserList = CollectionUtils.isEmpty(teamVerifyDTO.getNewAddMainUserList()) ? new HashSet<>() : teamVerifyDTO.getNewAddMainUserList();
        // 要删除的负责人
//        List<String> newDelMainUserList = teamVerifyDTO.getNewDelMainUserList();
        // 要添加的协同人
        Set<String> newAddCoUserList = CollectionUtils.isEmpty(teamVerifyDTO.getNewAddCoUserList()) ? new HashSet<>() : teamVerifyDTO.getNewAddCoUserList();
        // 要删除的协同人
//        List<String> newDelCoUserList = teamVerifyDTO.getNewDelCoUserList();
        // 是否继承
        Boolean isInheritance = teamVerifyDTO.getIsInheritance();
        // 批量标识
        Integer batchTag = teamVerifyDTO.getBatchTag();
        // 来自退回公海池操作
        Boolean fromBackPublic = teamVerifyDTO.getFromBackPublic();
        Integer operateTag = teamVerifyDTO.getOperateTag();

        TeamAfterVerifyDTO teamAfterVerifyDTO = new TeamAfterVerifyDTO();
        teamAfterVerifyDTO.setLoginUser(loginUser);
        teamAfterVerifyDTO.setCorpid(corpid);
        teamAfterVerifyDTO.setFormId(formId);
        teamAfterVerifyDTO.setSaasMark(saasMark);
        teamAfterVerifyDTO.setBusinessType(businessType);
        teamAfterVerifyDTO.setDistributorMark(distributorMark);
        teamAfterVerifyDTO.setDataId(dataIdIn);
        teamAfterVerifyDTO.setIsInheritance(isInheritance);
        teamAfterVerifyDTO.setFromDetail(teamVerifyDTO.getFromDetail());
        teamAfterVerifyDTO.setFromBackPublic(teamVerifyDTO.getFromBackPublic());
        //下面这个是为了公海池校验的时候用到，现在编辑页需要进行客户公海池捞取频率的校验
        teamAfterVerifyDTO.setIsNew(teamVerifyDTO.getIsNew());
        /*if (CollectionsUtil.isNotEmpty(newAddMainUserList) && CollectionsUtil.isNotEmpty(newAddCoUserList)) {
            teamAfterVerifyDTO.setTeamUserId(newAddMainUserList.get(BasicConstant.ZERO));
        }*/

        // 获取负责人/协同人字段解释
        TeamFieldExplainPOJO teamFieldExplainPOJO = proFormHelp.getTeamFieldExplain(corpid, formId, businessType);
        // 负责人解释
        FieldAttrEntity ownerField = teamFieldExplainPOJO.getOwnerField();
        Integer feeType = commonHelp.getCurrentCompanyPackage(corpid);
        if (Objects.nonNull(ownerField)) {
            Integer multiple = ownerField.getMultiple();
            if (Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType())) {
                if (Objects.isNull(multiple)) {
                    FormOwnerUniqueEnum formOwnerUniqueEnum = FormOwnerUniqueEnum.getFormOwnerUniqueByBus(businessType);
                    if (Objects.nonNull(formOwnerUniqueEnum)) {
                        ownerField.setMultiple(formOwnerUniqueEnum.getValue());
                    }
                }
            }else {
                FormOwnerUniqueEnum formOwnerUniqueEnum = FormOwnerUniqueEnum.getFormOwnerUniqueByBus(businessType);
                if (Objects.nonNull(formOwnerUniqueEnum)) {
                    ownerField.setMultiple(formOwnerUniqueEnum.getValue());
                }
            }
        }

        // 协同人解释
        FieldAttrEntity coUserField = teamFieldExplainPOJO.getCoUserField();
        //协同人可编辑权限
        Integer formPermission = null;
        if (Objects.nonNull(coUserField)) {
            formPermission = coUserField.getFormPermission();
            if (Objects.isNull(formPermission)) {
                formPermission = FormCoUserDefaultPermissionEnum.getDefaultPerByBus(businessType);
            }
        }
        // 离职人员处理,注意现在不管是哪个界面、哪个功能对离职校验都是一样的，都是只有一个负责人，并且这个负责人是离职的，才会提示，其它场景不提示
        Set<String> delUserIdList = new HashSet<> ((Set<String>) CloneUtil.deepClone(newAddMainUserList));
        if (CollectionsUtil.isNotEmpty(newAddCoUserList)) {
            delUserIdList.addAll(newAddCoUserList);
        }
        Map<String, Object> param = new HashMap<>();
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, BasicConstant.ONE);
        param.put(ParameterConstant.USER_ID_IN, delUserIdList);
        delUserIdList = new HashSet<>(userModel.getUserIds(param));


        // 共享/隔离处理
        // 获取共享/隔离配置
        FormTeamSetEntity formTeamSetEntity = getFormTeamSet(corpid, formId, saasMark, businessType, distributorMark);

        // 有共享/隔离的业务
        Integer model = formTeamSetEntity.getModel();
        //非旗舰版套餐默认走通用规则，旗舰版套餐就需要各种判断了。以及未设置过共享或隔离的走默认规则
        if (Objects.isNull(model) || !Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType())) {
            model = FormDefaultPatternEnum.getModelValueByBusinessType(businessType);
            formTeamSetEntity.setModel(model);
        }
        Map<String, Set<String>> addMainUserMap = new HashMap<>();
        Map<String, Set<String>> addCoUserMap = new HashMap<>();
        Map<String, Set<String>> delMainUserMap = new HashMap<>();
        Map<String, Set<String>> delCoUserMap = new HashMap<>();
        Map<String, Set<String>> updateMainToCoUserMap = new HashMap<>();
        Map<String, Set<String>> updateCoToMainUserMap = new HashMap<>();


        List<TeamBatchPojo> teamBatchPojos = new ArrayList<>();
        boolean delVerfifyTag = (Objects.equals(SaasMarkEnum.PAAS.getCode(), saasMark) && Objects.nonNull(ownerField)) ||
                Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark);
        if (teamVerifyDTO.getIsNew()) {
            // 新建
            // 校校验离职人员有个特殊场景，如果负责人中只要有一个员工在职才不校验
            if (delVerfifyTag && CollectionsUtil.isNotEmpty(newAddMainUserList)) {
                Set<String> copyDelAllList = new HashSet<>(((Set<String>) CloneUtil.deepClone(delUserIdList)));
                Set<String> copyDelAddMainUserList = new HashSet<>(((Set<String>) CloneUtil.deepClone(newAddMainUserList)));
                copyDelAddMainUserList.removeAll(copyDelAllList);
                if (CollectionsUtil.isEmpty(copyDelAddMainUserList) || copyDelAddMainUserList.size() == BasicConstant.ZERO) {
                    TeamBatchPojo teamBatchPojo = new TeamBatchPojo();
                    teamBatchPojo.setCode(SystemErrorCodeEnum.API_ERROR_100127.getCode());
                    teamBatchPojo.setFailMsg(I18nMessageUtil.getMessage(TeamMembersConstant.NEW_FAIL_MESSAGE));
                    teamBatchPojo.setFailMsgReason(SystemErrorCodeEnum.API_ERROR_100127.getMsg());
                    teamBatchPojos.add(teamBatchPojo);
                    // 报错直接返回
                    teamAfterVerifyDTO.setTeamBatchPojos(teamBatchPojos);
                    return teamAfterVerifyDTO;
                }
            }
            // 负责人和协同人有重复数据
            if (ExplainUtil.judgeListContainsAnotherListOneValue(new ArrayList<>(newAddMainUserList), new ArrayList<>(newAddCoUserList))) {
                newAddMainUserList.retainAll(newAddCoUserList);

                List<UserEntity> userList = userModel.getByUserIdIn(corpid, newAddMainUserList, true);
                StringBuilder errorUserName = new StringBuilder();
                String errorUser = "";
                for (UserEntity userEntity : userList) {
                    errorUserName.append(userEntity.getName()).append(StringConstant.COMMA);
                }
                if (!errorUserName.toString().isEmpty()) {
                    errorUser = errorUserName.substring(0, errorUserName.length() - 1);
                }

                TeamBatchPojo teamBatchPojo = new TeamBatchPojo();
                teamBatchPojo.setCode(BuinessDefaultErrorCodeEnum.API_ERROR_200024.getCode());
                teamBatchPojo.setFailMsg(I18nMessageUtil.getMessage(TeamMembersConstant.NEW_FAIL_MESSAGE));
                teamBatchPojo.setFailMsgReason(String.format(BuinessDefaultErrorCodeEnum.API_ERROR_200024.getMsg(), errorUser));
                teamBatchPojos.add(teamBatchPojo);

                // 报错直接返回
                teamAfterVerifyDTO.setTeamBatchPojos(teamBatchPojos);
                return teamAfterVerifyDTO;
            }

            for (Long dataId : dataIdIn) {
                if (!teamVerifyDTO.getFromApproval()) {
                    // 不是审批的需要校验
                    // 操作权限校验
                    TeamBatchPojo teamBatchPojo = verifyPermissions(corpid, userId, creatorId, loginUser, newAddMainUserList, null, newAddCoUserList, null, ownerField, coUserField, null, null, isInheritance, fromBackPublic, teamVerifyDTO.getPaasOwnUserFromOwnTag(),
                            null, dataId, operateTag);

                    // 报错处理
                    if (Objects.nonNull(teamBatchPojo)) {
                        teamBatchPojos.add(teamBatchPojo);
                        continue;
                    }
                }

                TeamModelProcessMidPOJO teamModelProcessMidPOJO = new TeamModelProcessMidPOJO(model, corpid, dataId, businessType, newAddMainUserList, null, null, null, newAddCoUserList, null, isInheritance, ownerField, coUserField,
                        new HashSet<>(), new HashSet<>(), loginUser, teamVerifyDTO.getFromDetail(), null, null, null, null, fromBackPublic, operateTag, teamVerifyDTO.getSaasMark(),teamVerifyDTO.getTeamUserId(),teamVerifyDTO.getPlatform(), teamVerifyDTO.getFromCover(), formId);
                // 隔离/共享规则处理
                TeamAfterModeProcessPOJO teamAfterModeProcessPOJO = shareAndIsolationModeProcess(teamModelProcessMidPOJO);
                // 报错处理
                TeamBatchPojo batchPojo = teamAfterModeProcessPOJO.getTeamBatchPojo();
                if (Objects.nonNull(batchPojo)) {
                    teamBatchPojos.add(batchPojo);
                    continue;
                }

                addMainUserMap.put(String.valueOf(dataId), teamAfterModeProcessPOJO.getAddMainUserList());
                addCoUserMap.put(String.valueOf(dataId), teamAfterModeProcessPOJO.getAddCoUserList());
                teamAfterVerifyDTO.setTeamUserId(teamAfterModeProcessPOJO.getTeamUserId());
            }


        } else {
            // 编辑
            // 获取老的团队数据
            TeamUserListPOJO teamUserListPOJO = getTeamOldUserList(corpid, formId, businessType, subBusinessType, dataIdIn, model);
            // 老的团队所有成员
            Map<Long, Set<String>> oldUserMap = teamUserListPOJO.getOldUserMap();
            // 老的负责人和协同人
            Map<Long, Set<String>> oldMainUserMap = teamUserListPOJO.getOldMainUserMap();
            Map<Long, Set<String>> oldCoUserMap = teamUserListPOJO.getOldCoUserMap();
            //这边需要检验一下离职
            for (Long dataId : dataIdIn) {
                //校验离职人员有个特殊场景，如果负责人中只要有一个员工在职才不校验
                if (delVerfifyTag && CollectionsUtil.isNotEmpty(newAddMainUserList)) {
                    Set<String> copyDelAllList = new HashSet<>(((Set<String>) CloneUtil.deepClone(delUserIdList)));
                    Set<String> copyDelAddMainUserList = new HashSet<>(((Set<String>) CloneUtil.deepClone(newAddMainUserList)));
                    copyDelAddMainUserList.removeAll(copyDelAllList);
                    if (CollectionsUtil.isEmpty(copyDelAddMainUserList) || copyDelAddMainUserList.size() == BasicConstant.ZERO) {
                        TeamBatchPojo teamBatchPojo = new TeamBatchPojo(SystemErrorCodeEnum.API_ERROR_100127.getCode(), SystemErrorCodeEnum.API_ERROR_100127.getMsg(),
                                null, UserTeamOperateTagEnum.TEAM_USER_ALL_OPERATE.getName(), dataId);
                        teamBatchPojos.add(teamBatchPojo);
                        continue;
                    }
                }
                Set<String> oldMainUserList = oldMainUserMap.getOrDefault(dataId, new HashSet<>());
                Set<String> oldCoUserList = oldCoUserMap.getOrDefault(dataId, new HashSet<>());

                Set<String> copyNewAddMainList = new HashSet<>(((Set<String>) CloneUtil.deepClone(newAddMainUserList)));
                // 获得实际添加的负责人
                copyNewAddMainList.removeAll(oldMainUserList);

                Set<String> copyOldMainList = new HashSet<>(((Set<String>) CloneUtil.deepClone(oldMainUserList)));
                // 获得删除的负责人
                copyOldMainList.removeAll(newAddMainUserList);

                Set<String> copyNewCoUserList = new HashSet<>(((Set<String>) CloneUtil.deepClone(newAddCoUserList)));
                // 获得实际要添加的协同人
                copyNewCoUserList.removeAll(oldCoUserList);

                Set<String> copyOldCoUserList =  new HashSet<>(((Set<String>) CloneUtil.deepClone(oldCoUserList)));
                // 获得实际要删除的协同人
                copyOldCoUserList.removeAll(newAddCoUserList);

                Set<String> copyDelCoUserList = new HashSet<>(((Set<String>) CloneUtil.deepClone(copyOldCoUserList)));

                //协同人升级为负责人时,
                if (ExplainUtil.judgeListContainsAnotherListOneValue(new ArrayList<>(copyNewAddMainList), new ArrayList<>(copyOldCoUserList))) {
                    // 获得协同人要升级成负责人的人
                    copyDelCoUserList.retainAll(copyNewAddMainList);
                    // 去除要升级成负责人的人，取得要实际添加的负责人和要删除的协同人
                    copyNewAddMainList.removeAll(copyDelCoUserList);
                    copyOldCoUserList.removeAll(copyDelCoUserList);

                    updateCoToMainUserMap.put(String.valueOf(dataId), copyDelCoUserList);
                }

                Set<String> copyDelMainUserList = new HashSet<>(((Set<String>) CloneUtil.deepClone(copyOldMainList)));
                // 负责人降级为协同人
                if (ExplainUtil.judgeListContainsAnotherListOneValue(new ArrayList<>(copyOldMainList), new ArrayList<>(copyNewCoUserList))) {
                    // 获取降级的人员
                    copyDelMainUserList.retainAll(copyNewCoUserList);
                    // 去除要降级成协同人的人，取得实际要删除的负责人和添加的协同人
                    copyOldMainList.removeAll(copyDelMainUserList);
                    copyNewCoUserList.removeAll(copyDelMainUserList);

                    updateMainToCoUserMap.put(String.valueOf(dataId), copyDelMainUserList);
                }

                // todo 离职人员特殊处理 感觉老逻辑有问题，先这样，测试后再看看

                if (!teamVerifyDTO.getFromApproval()) {
                    // 权限校验
                    TeamBatchPojo teamBatchPojo = verifyPermissions(corpid, userId, creatorId, loginUser, copyNewAddMainList, copyOldMainList, copyNewCoUserList, copyOldCoUserList, ownerField, coUserField, oldMainUserList, oldCoUserList, isInheritance, fromBackPublic, teamVerifyDTO.getPaasOwnUserFromOwnTag(), null, dataId, operateTag);
                    // 报错处理
                    if (Objects.nonNull(teamBatchPojo)) {
                        teamBatchPojos.add(teamBatchPojo);
                        continue;
                    }
                }

                TeamModelProcessMidPOJO teamModelProcessMidPOJO = new TeamModelProcessMidPOJO(model, corpid, dataId, businessType, copyNewAddMainList, updateCoToMainUserMap.getOrDefault(String.valueOf(dataId), new HashSet<>()), updateMainToCoUserMap.getOrDefault(String.valueOf(dataId), new HashSet<>()), copyOldMainList, copyNewCoUserList, copyOldCoUserList, isInheritance, ownerField, coUserField,
                        oldMainUserList, oldCoUserList, loginUser, teamVerifyDTO.getFromDetail(), null, null, null, null, fromBackPublic, operateTag, teamVerifyDTO.getSaasMark(),teamVerifyDTO.getTeamUserId(),teamVerifyDTO.getPlatform(), teamVerifyDTO.getFromCover(), formId);
                // 共享/隔离处理
                TeamAfterModeProcessPOJO teamAfterModeProcessPOJO = shareAndIsolationModeProcess(teamModelProcessMidPOJO);

                // 报错处理
                TeamBatchPojo batchPojo = teamAfterModeProcessPOJO.getTeamBatchPojo();
                if (Objects.nonNull(batchPojo)) {
                    teamBatchPojos.add(batchPojo);
                    continue;
                }

                addMainUserMap.put(String.valueOf(dataId), teamAfterModeProcessPOJO.getAddMainUserList());
                delMainUserMap.put(String.valueOf(dataId), teamAfterModeProcessPOJO.getDelMainUserList());
                addCoUserMap.put(String.valueOf(dataId), teamAfterModeProcessPOJO.getAddCoUserList());
                delCoUserMap.put(String.valueOf(dataId), teamAfterModeProcessPOJO.getDelCoUserList());

            }

        }



        teamAfterVerifyDTO.setTeamBatchPojos(teamBatchPojos);
        teamAfterVerifyDTO.setAddMainUserMap(addMainUserMap);
        teamAfterVerifyDTO.setDelMainUserMap(delMainUserMap);
        teamAfterVerifyDTO.setAddCoUserMap(addCoUserMap);
        teamAfterVerifyDTO.setDelCoUserMap(delCoUserMap);
        teamAfterVerifyDTO.setUpdateToMainUserMap(updateCoToMainUserMap);
        teamAfterVerifyDTO.setUpdateToCoUserMap(updateMainToCoUserMap);
        teamAfterVerifyDTO.setFormTeamSetEntity(formTeamSetEntity);
        teamAfterVerifyDTO.setEditFormPermission(formPermission);
        teamAfterVerifyDTO.setFromCheckRepeatForm(teamVerifyDTO.getFromCheckRepeatForm());
        return teamAfterVerifyDTO;
    }

    protected FormTeamSetEntity getFormTeamSet(String corpid, Long formId, Integer saasMark, Integer businessType, Integer distributorMark) throws XbbException {
        return null;
    }

    protected TeamAfterModeProcessPOJO shareAndIsolationModeProcess(TeamModelProcessMidPOJO teamModelProcessMidPOJO) throws XbbException {
        return null;
    }

    protected TeamUserListPOJO getTeamOldUserList(String corpid, Long formId, Integer businessType, Integer subBusinessType, List<Long> dataIdIn, Integer model) throws XbbException {
        // 老的团队所有成员
        Map<Long, Set<String>> oldUserMap = new HashMap<>();
        // 老的负责人和协同人以及隔离模式下每个小团队负责人和协同人的对应关系
        Map<Long, Set<String>> oldMainUserMap = new HashMap<>();
        Map<Long, Set<String>> oldCoUsrMap = new HashMap<>();
        Map<Long, Map<String, Set<String>>> oldTeamCoUserMap = new HashMap<>();
        if (UserTeamEnum.hasTeam(businessType)) {
            boolean isPublic = Objects.equals(XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode(), subBusinessType) || Objects.equals(XbbRefTypeEnum.CLUE_PUBLIC.getCode(), subBusinessType);
            List<UserTeamEntity> userTeamList = getUserTeamList(dataIdIn, corpid, businessType, isPublic);
            for (UserTeamEntity userTeam : userTeamList) {
                oldUserMap.computeIfAbsent(userTeam.getDataId(), v -> new HashSet<>()).add(userTeam.getUserId());
                if (Objects.equals(userTeam.getIsMain(), BasicConstant.ONE)) {
                    oldMainUserMap.computeIfAbsent(userTeam.getDataId(), v -> new HashSet<>()).add(userTeam.getUserId());
                } else {
                    oldCoUsrMap.computeIfAbsent(userTeam.getDataId(), v -> new HashSet<>()).add(userTeam.getUserId());
                }
            }
            if (Objects.equals(model, FormPatternEnum.FORM_ISOLATION.getModel())) {
                for (Map.Entry<Long, Set<String>> entry: oldMainUserMap.entrySet()) {
                    Long dataId = entry.getKey();
                    Set<String> mainUserIdList = entry.getValue();
                    Map<String, Set<String>> teamCoUserMap = new HashMap<>();
                    for (String mainUserId : mainUserIdList) {
                        Set<String> coUserList = new HashSet<>();
                        for (UserTeamEntity userTeamEntity : userTeamList) {
                            if (Objects.nonNull(userTeamEntity.getTeamUserId())
                                    && Objects.equals(mainUserId, userTeamEntity.getTeamUserId()) && Objects.equals(userTeamEntity.getIsMain(), BasicConstant.ZERO)) {
                                coUserList.add(userTeamEntity.getUserId());
                            }
                        }
                        teamCoUserMap.put(mainUserId, coUserList);
                    }
                    oldTeamCoUserMap.put(dataId, teamCoUserMap);
                }
            }
        }

        TeamUserListPOJO teamUserListPOJO = new TeamUserListPOJO();
        teamUserListPOJO.setOldUserMap(oldUserMap);
        teamUserListPOJO.setOldMainUserMap(oldMainUserMap);
        teamUserListPOJO.setOldCoUserMap(oldCoUsrMap);
        teamUserListPOJO.setOldTeamCoUserMap(oldTeamCoUserMap);
        return teamUserListPOJO;
    }

    protected List<UserTeamEntity> getUserTeamList(List<Long> dataIdList, String corpid, Integer businessType, Boolean isPublic) {
        return new ArrayList<>();
    }
    /**
     * Description: 负责人/协同人操作权限校验
     * @param corpid
     * @param userId
     * @param creatorId
     * @param loginUser
     * @param newAddMainUserList
     * @param newDelMainUserList
     * @param newAddCoUserList
     * @param newDelCoUserList
     * @param ownerField
     * @param coUserField
     * @param oldMainUserList
     * @param oldCoUserList
     * @param isInheritance
     * @param fromBackPublic
     * @param paasOwnUserFromOwnTag
     * @param nameOrSeriNoMap
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2022/1/10 14:09
     * @since
     */
    public TeamBatchPojo verifyPermissions(String corpid, String userId, String creatorId, UserVO loginUser, Set<String> newAddMainUserList, Set<String> newDelMainUserList, Set<String> newAddCoUserList, Set<String> newDelCoUserList, FieldAttrEntity ownerField, FieldAttrEntity coUserField, Set<String> oldMainUserList, Set<String> oldCoUserList, Boolean isInheritance, Boolean fromBackPublic,
                                           Boolean paasOwnUserFromOwnTag, Map<Long, String> nameOrSeriNoMap, Long dataId, Integer operateTag) throws XbbException {
        String errorName = Objects.nonNull(nameOrSeriNoMap) ? nameOrSeriNoMap.get(dataId) : null;
        // 继承或者来自退回公海池的操作不进行字段权限校验
        if (isInheritance || fromBackPublic) {
            return null;
        }

        TeamBatchPojo teamBatchPojo = null;
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        if (Objects.isNull(userEntity)) {
            teamBatchPojo = new TeamBatchPojo();
            teamBatchPojo.setCode(SystemErrorCodeEnum.API_ERROR_100004.getCode());
            teamBatchPojo.setDataId(dataId);
            commonHelp.singleFailMsg(errorName, UserTeamOperateTagEnum.TEAM_USER_ALL_OPERATE.getName(), teamBatchPojo);
            teamBatchPojo.setFailMsgReason(SystemErrorCodeEnum.API_ERROR_100004.getMsg());
            return teamBatchPojo;
        }
        List<String> subIdList = userModel.getManageUser(userEntity);

        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        handlerExplainDTO.setUserId(userId);
        handlerExplainDTO.setCreatorId(creatorId);
        handlerExplainDTO.setCoUserId(CollectionUtils.isEmpty(oldCoUserList) ? new ArrayList<>() : new ArrayList<>(oldCoUserList));
        handlerExplainDTO.setOwnerId(CollectionUtils.isEmpty(oldMainUserList) ? new ArrayList<>() : new ArrayList<>(oldMainUserList));
        handlerExplainDTO.setSubIdList(subIdList);
        handlerExplainDTO.setLoginUser(loginUser);

        // 添加/删除负责人权限判断
        if (CollectionUtils.isNotEmpty(newAddMainUserList)) {
            //paas表单只有拖进负责人字段并且负责人字段有值才需要校验，否则不需要校验，因为强制用创建人id作为负责人id
            if (paasOwnUserFromOwnTag) {
                if (Objects.nonNull(ownerField)) {
                    Boolean havePermission = ExplainUtil.advancedOperationHavePermission(ownerField, handlerExplainDTO, FieldAdvanceOperationEnum.ADD.getOperation());
                    if (!havePermission) {
                        teamBatchPojo = new TeamBatchPojo();
                        teamBatchPojo.setCode(UserTeamErrorCodeEnum.API_ERROR_390007.getCode());
                        if (Objects.equals(UserTeamOperateTagEnum.ADD_TEAM_TAG.getOperateTag(), operateTag)) {
                            commonHelp.singleFailMsg(errorName, UserTeamOperateTagEnum.ADD_TEAM_TAG.getName(), teamBatchPojo);
                        }else if (Objects.equals(UserTeamOperateTagEnum.DISTRIBUTION.getOperateTag(), operateTag)) {
                            commonHelp.singleFailMsg(errorName, UserTeamOperateTagEnum.DISTRIBUTION.getName(), teamBatchPojo);
                        }else {
                            commonHelp.singleFailMsg(errorName, UserTeamOperateTagEnum.ADD_MAIN.getName(), teamBatchPojo);
                        }
                        teamBatchPojo.setDataId(dataId);
                        teamBatchPojo.setFailMsgReason(UserTeamErrorCodeEnum.API_ERROR_390007.getMsg());
                        return teamBatchPojo;
                    }
                }
            }
        }

        if (CollectionUtils.isNotEmpty(newDelMainUserList)) {
            if (Objects.nonNull(ownerField)) {
                Boolean havePermission = ExplainUtil.advancedOperationHavePermission(ownerField, handlerExplainDTO, FieldAdvanceOperationEnum.DEL.getOperation());
                if (!havePermission) {
                    teamBatchPojo = new TeamBatchPojo();
                    teamBatchPojo.setCode(UserTeamErrorCodeEnum.API_ERROR_390005.getCode());
                    if (Objects.equals(UserTeamOperateTagEnum.DEL_TEAM_TAG.getOperateTag(), operateTag)) {
                        commonHelp.singleFailMsg(errorName, UserTeamOperateTagEnum.DEL_TEAM_TAG.getName(), teamBatchPojo);
                    }else {
                        commonHelp.singleFailMsg(errorName, UserTeamOperateTagEnum.DEL_MAIN.getName(), teamBatchPojo);
                    }
                    teamBatchPojo.setDataId(dataId);
                    teamBatchPojo.setFailMsgReason(UserTeamErrorCodeEnum.API_ERROR_390005.getMsg());
                    return teamBatchPojo;
                }
            }
        }

        // 添加/删除协同人权限判断
        if (CollectionUtils.isNotEmpty(newAddCoUserList)) {
            if (Objects.nonNull(coUserField)) {
                Boolean havePermission = ExplainUtil.advancedOperationHavePermission(coUserField, handlerExplainDTO, FieldAdvanceOperationEnum.ADD.getOperation());
                if (!havePermission) {
                    teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_390008.getCode(), UserTeamErrorCodeEnum.API_ERROR_390008.getMsg(), errorName, UserTeamOperateTagEnum.ADD_COUSER.getName(),
                            dataId);
                    return teamBatchPojo;
                }
            }
        }

        if (CollectionUtils.isNotEmpty(newDelCoUserList)) {
            if (Objects.nonNull(coUserField)) {
                Boolean havePermission = ExplainUtil.advancedOperationHavePermission(coUserField, handlerExplainDTO, FieldAdvanceOperationEnum.DEL.getOperation());
                if (!havePermission) {
                    teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_390006.getCode(), UserTeamErrorCodeEnum.API_ERROR_390006.getMsg(), errorName,
                            UserTeamOperateTagEnum.DEL_COUSER.getName(), dataId);
                }
            }
        }
        return teamBatchPojo;
    }

    @Override
    public AfterSavePojo saveUserTeam(SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo, Long dataId, PaasFormDataEntity newPaasFormDataEntity, Integer isImport, Boolean workflowTag) throws XbbException {
        AfterSavePojo afterSavePojo = new AfterSavePojo();
        Integer updateLine = BasicConstant.ZERO;
        if (Objects.nonNull(saasNeedRedundantAttrPoJo)) {
            TeamAfterVerifyDTO teamAfterVerifyDTO = saasNeedRedundantAttrPoJo.getTeamAfterVerifyDTO();
            if (Objects.nonNull(teamAfterVerifyDTO)) {
                teamAfterVerifyDTO.setDataId(new ArrayList<>(Arrays.asList(dataId)));
                //因为这边主业务成功了，所以能拿到主业务dataId,需要给key为null的map,重新赋值一下key
                Map<String, Set<String>> addMainUserMap = teamAfterVerifyDTO.getAddMainUserMap();
                Map<String, Set<String>> delMainUserMap = teamAfterVerifyDTO.getDelMainUserMap();
                Map<String, Set<String>> addCoUserMap = teamAfterVerifyDTO.getAddCoUserMap();
                Map<String, Set<String>> delCoUserMap = teamAfterVerifyDTO.getDelCoUserMap();
                Map<String, Set<String>> updateToMainUserMap = teamAfterVerifyDTO.getUpdateToMainUserMap();
                Map<String, Set<String>> updateToCoUserMap = teamAfterVerifyDTO.getUpdateToCoUserMap();
                updateLine = getLatestMap(addMainUserMap,dataId, updateLine);
                updateLine = getLatestMap(delMainUserMap,dataId, updateLine);
                updateLine = getLatestMap(addCoUserMap,dataId, updateLine);
                updateLine = getLatestMap(delCoUserMap,dataId, updateLine);
                updateLine = getLatestMap(updateToMainUserMap,dataId, updateLine);
                updateLine = getLatestMap(updateToCoUserMap,dataId, updateLine);
                TeamSaveMiddlePojo teamSaveMiddlePojo = new TeamSaveMiddlePojo();
                teamSaveMiddlePojo.setWorkFlowTag(workflowTag);
                teamAfterVerifyDTO.setTeamSaveMiddlePojo(teamSaveMiddlePojo);
                teamAfterVerifyDTO.setPaasFormDataEntity(newPaasFormDataEntity);
                teamAfterVerifyDTO.setIsImport(isImport);
                businessSave(teamAfterVerifyDTO);
                //因为可能会有些报错，但是不抛出，用于后续排查问题
                List<TeamBatchPojo> teamBatchPojos = teamAfterVerifyDTO.getTeamBatchPojos();
                if (CollectionsUtil.isNotEmpty(teamBatchPojos)) {
                    LOG.error("============保存团队异常==：{}", String.valueOf(teamBatchPojos));
                }

            }
        }

        afterSavePojo.setUpdateLine(updateLine);
        return afterSavePojo;
    }

    /**
     * Description: 封装团队数据
     * @param teamAfterVerifyDTO
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2022/1/4 15:50
     * @since
     */
    public TeamAfterFormatDTO formatTeam(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {
        String corpid = teamAfterVerifyDTO.getCorpid();
        Integer businessType = teamAfterVerifyDTO.getBusinessType();
        String teamUserId = teamAfterVerifyDTO.getTeamUserId();
        String teamName = teamAfterVerifyDTO.getTeamName();
        Integer saasMark = teamAfterVerifyDTO.getSaasMark();
        List<Long> dataIdIn = teamAfterVerifyDTO.getDataId();
        Integer editFormPermission = teamAfterVerifyDTO.getEditFormPermission();
        Map<String, Set<String>> addMainUserMap = teamAfterVerifyDTO.getAddMainUserMap();
        Map<String, Set<String>> delMainUserMap = teamAfterVerifyDTO.getDelMainUserMap();
        Map<String, Set<String>> addCoUserMap = teamAfterVerifyDTO.getAddCoUserMap();
        Map<String, Set<String>> delCoUserMap = teamAfterVerifyDTO.getDelCoUserMap();
        Map<String, Set<String>> updateToMainUserMap = teamAfterVerifyDTO.getUpdateToMainUserMap();
        Map<String, Set<String>> updateToCoUserMap = teamAfterVerifyDTO.getUpdateToCoUserMap();
        Map<String, Map<String, Set<String>>> changeTeamMainUserMap = teamAfterVerifyDTO.getChangeTeamMainUserMap();

        // 封装要操作的团队数据
        // 需要新增的团队数据
        List<UserTeamEntity> userTeamAddList = new ArrayList<>();
        // 需要更新成负责人的数据
        List<UserTeamEntity> updateUserToMainTeamList = new ArrayList<>();
        // 需要更新成协同人的数据
        List<UserTeamEntity> updateUserToCoTeamList = new ArrayList<>();
        // 需要删除的团队数据
        List<UserTeamEntity> userTeamDeleteList = new ArrayList<>();
        // 需要更新团队协同人的负责人信息
        List<UserTeamEntity> updateUserTeamMainList = new ArrayList<>();
        List<TeamBatchPojo> teamBatchPojos = new ArrayList<>();
        if (Objects.nonNull(addMainUserMap)) {
            for (Map.Entry<String, Set<String>> entry : addMainUserMap.entrySet()) {
                Set<String> addMainUserList = entry.getValue();
                if (CollectionUtils.isNotEmpty(addMainUserList)) {
                    List<UserEntity> userEntities = new ArrayList<>();
                    if (Objects.equals(SaasMarkEnum.PAAS.getCode(), saasMark)) {
                        userEntities = userModel.getByUserIdIn(corpid, addMainUserList, false);
                    }else {
                        userEntities = userModel.getByUserIdIn(corpid, addMainUserList, true);
                    }
                    Map<String, UserEntity> userEntityMap = userEntities.stream().collect(Collectors.toMap(UserEntity::getUserId, v -> v));
                    for (String userId : addMainUserList) {
                        UserEntity userEntity = userEntityMap.get(userId);
                        if (Objects.isNull(userEntity)) {
                            TeamBatchPojo teamBatchPojo = new TeamBatchPojo();
                            teamBatchPojo.setCode(SystemErrorCodeEnum.API_ERROR_100127.getCode());
                            teamBatchPojo.setFailMsgReason(SystemErrorCodeEnum.API_ERROR_100127.getMsg());
                            teamBatchPojos.add(teamBatchPojo);
                            continue;
                        }
                        UserTeamEntity userTeamEntity = new UserTeamEntity();
                        userTeamEntity.setCorpid(userEntity.getCorpid());
                        userTeamEntity.setUserId(userEntity.getUserId());
                        userTeamEntity.setUserName(userEntity.getName());
                        userTeamEntity.setUserAvatar(userEntity.getAvatar());
                        userTeamEntity.setIsMain(BasicConstant.MAIN_USER);
                        userTeamEntity.setDataId((Objects.isNull(entry.getKey()) || Objects.equals(entry.getKey(), "0") || Objects.equals(entry.getKey(), "null")) ? dataIdIn.get(BasicConstant.ZERO) : Long.parseLong(entry.getKey()));
                        userTeamEntity.setName(teamName);
                        userTeamAddList.add(userTeamEntity);
                    }
                }
            }
        }
        if (Objects.nonNull(delMainUserMap)) {
            for (Map.Entry<String, Set<String>> entry : delMainUserMap.entrySet()) {
                Set<String> delMainUserList = entry.getValue();
                if (CollectionUtils.isNotEmpty(delMainUserList)) {
                    Map<String, Object> param = new HashMap<>();
                    param.put(ParameterConstant.CORPID, corpid);
                    param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                    param.put(ParameterConstant.IS_MAIN, BasicConstant.MAIN_USER);
                    if (Objects.equals(XbbRefTypeEnum.WAREHOUSE.getCode(), businessType)) {
                        param.put("relationIdIn", delMainUserList);
                    }else {
                        param.put(ParameterConstant.USER_ID_IN, delMainUserList);
                    }
                    List<UserTeamEntity> userTeamList = getUserTeamListByParams(Collections.singletonList(Long.parseLong(entry.getKey())), businessType, param);
                    userTeamDeleteList.addAll(userTeamList);
                }
            }
        }

        if (Objects.nonNull(addCoUserMap)) {
            for (Map.Entry<String, Set<String>> entry : addCoUserMap.entrySet()) {
                Set<String> addCoUserList = entry.getValue();
                if (CollectionUtils.isNotEmpty(addCoUserList)) {
                    List<UserEntity> userEntities = userModel.getByUserIdIn(corpid, addCoUserList, true);
                    Map<String, UserEntity> userEntityMap = userEntities.stream().collect(Collectors.toMap(UserEntity::getUserId, v -> v));
                    for (String userId : addCoUserList) {
                        UserEntity userEntity = userEntityMap.get(userId);
                        if (Objects.isNull(userEntity)) {
                            TeamBatchPojo teamBatchPojo = new TeamBatchPojo();
                            teamBatchPojo.setCode(SystemErrorCodeEnum.API_ERROR_100127.getCode());
                            teamBatchPojo.setFailMsgReason(SystemErrorCodeEnum.API_ERROR_100127.getMsg());
                            teamBatchPojos.add(teamBatchPojo);
                            continue;
                        }
                        UserTeamEntity userTeamEntity = new UserTeamEntity();
                        userTeamEntity.setCorpid(userEntity.getCorpid());
                        userTeamEntity.setUserId(userEntity.getUserId());
                        userTeamEntity.setUserName(userEntity.getName());
                        userTeamEntity.setUserAvatar(userEntity.getAvatar());
                        userTeamEntity.setIsMain(BasicConstant.COOP_USER);
                        //从form页的新增界面过来，entry.getKey为null，这时候dataIdIn也只可能只会有一条数据，所以能直接取第一个
                        userTeamEntity.setDataId((Objects.isNull(entry.getKey()) || Objects.equals(entry.getKey(), "0") || Objects.equals(entry.getKey(), "null")) ? dataIdIn.get(BasicConstant.ZERO) : Long.parseLong(entry.getKey()));
                        userTeamEntity.setTeamUserId(teamUserId);
                        userTeamEntity.setFormPermission(editFormPermission);
                        userTeamAddList.add(userTeamEntity);
                    }
                }
            }
        }

        if (Objects.nonNull(delCoUserMap)) {
            for (Map.Entry<String, Set<String>> entry : delCoUserMap.entrySet()) {
                Set<String> delCoUserList = entry.getValue();
                if (CollectionUtils.isNotEmpty(delCoUserList)) {
                    Map<String, Object> param = new HashMap<>();
                    param.put(ParameterConstant.CORPID, corpid);
                    param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                    param.put(ParameterConstant.IS_MAIN, BasicConstant.COOP_USER);
                    param.put(ParameterConstant.USER_ID_IN, delCoUserList);
                    if (StringUtil.isNotEmpty(teamUserId)) {
                        param.put("teamUserId", teamUserId);
                    }
                    List<UserTeamEntity> userTeamList = getUserTeamListByParams(Collections.singletonList(Long.parseLong(entry.getKey())), businessType, param);
                    userTeamDeleteList.addAll(userTeamList);
                }
            }
        }

        if (Objects.nonNull(updateToMainUserMap)) {
            for (Map.Entry<String, Set<String>> entry : updateToMainUserMap.entrySet()) {
                Set<String> updateToMainUserList = entry.getValue();
                if (CollectionsUtil.isNotEmpty(updateToMainUserList)) {
                    Map<String, Object> param = new HashMap<>();
                    param.put(ParameterConstant.CORPID, corpid);
                    param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                    param.put(ParameterConstant.USER_ID_IN, updateToMainUserList);
                    List<UserTeamEntity> userTeamList = getUserTeamListByParams(Collections.singletonList(Long.parseLong(entry.getKey())), businessType, param);
                    updateUserToMainTeamList.addAll(userTeamList);
                }
            }
        }

        if (Objects.nonNull(updateToCoUserMap)) {
            for (Map.Entry<String, Set<String>> entry : updateToCoUserMap.entrySet()) {
                Set<String> updateToCoUserList = entry.getValue();
                if (CollectionsUtil.isNotEmpty(updateToCoUserList)) {
                    Map<String, Object> param = new HashMap<>();
                    param.put(ParameterConstant.CORPID, corpid);
                    param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                    param.put(ParameterConstant.USER_ID_IN, updateToCoUserList);
                    List<UserTeamEntity> userTeamList = getUserTeamListByParams(Collections.singletonList(Long.parseLong(entry.getKey())), businessType, param);
                    if (CollectionsUtil.isNotEmpty(userTeamList)) {
                        for (UserTeamEntity userTeamEntity : userTeamList) {
                            userTeamEntity.setFormPermission(editFormPermission);
                        }
                    }
                    updateUserToCoTeamList.addAll(userTeamList);
                }
            }
        }

        if (Objects.nonNull(changeTeamMainUserMap)) {
            for (Map.Entry<String, Map<String, Set<String>>> entry : changeTeamMainUserMap.entrySet()) {
                Map<String, Set<String>> shouldChangeTeamMainMap = entry.getValue();
                if (Objects.nonNull(shouldChangeTeamMainMap)) {
                    Optional<Set<String>> coUserList = shouldChangeTeamMainMap.values().stream().findFirst();
                    Optional<String> teamMainUserId = shouldChangeTeamMainMap.keySet().stream().findFirst();
                    Map<String, Object> param = new HashMap<>();
                    param.put(ParameterConstant.CORPID, corpid);
                    param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                    param.put(ParameterConstant.USER_ID_IN, coUserList.get());
                    List<UserTeamEntity> userTeamList = getUserTeamListByParams(Collections.singletonList(Long.parseLong(entry.getKey())), businessType, param);
                    for (UserTeamEntity userTeamEntity : userTeamList) {
                        userTeamEntity.setTeamUserId(teamMainUserId.get());
                        updateUserTeamMainList.add(userTeamEntity);
//                        if (Objects.nonNull(userTeamEntity.getTeamUserId())) {
//                        }
                    }
                }
            }
        }

        // 工作流拒绝，撤回数据特殊处理
        List<UserTeamEntity> userTeamList = getUserTeamListAndDel(dataIdIn, corpid, businessType, false, DelEnum.APPROVE_FAILED.getDel());
        if (CollectionsUtil.isNotEmpty(userTeamList)) {
            userTeamDeleteList.addAll(userTeamList);
        }
        if(CollectionUtils.isNotEmpty(teamAfterVerifyDTO.getTeamBatchPojos())){
            teamAfterVerifyDTO.getTeamBatchPojos().addAll(teamBatchPojos);
        }else{
            teamAfterVerifyDTO.setTeamBatchPojos(teamBatchPojos);
        }

        // 处理新加团队成员标签的初始化
        Set<String> userIds = userTeamAddList.stream().map(UserTeamEntity::getUserId).collect(Collectors.toSet());
        List<UserEntity> users = userModel.getByUserIdIn(corpid, userIds, false);
        Map<String, JSONArray> userIdAndLabelsMap = users.stream().filter(v -> Objects.nonNull(v.getLabels())).collect(Collectors.toMap(UserEntity::getUserId, user -> {
            JSONArray jsonArray = new JSONArray();
            user.getLabels().forEach(v -> {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(BasicConstant.ID, v);
                jsonObject.put(BasicConstant.TYPE, LabelTypeEnum.SYS_LABEL.getType());
                jsonArray.add(jsonObject);
            });
            return jsonArray;
        }));
        for (UserTeamEntity userTeamEntity : userTeamAddList) {
            userTeamEntity.setLabels(userIdAndLabelsMap.get(userTeamEntity.getUserId()));
        }

        TeamAfterFormatDTO teamAfterFormatDTO = new TeamAfterFormatDTO();
        teamAfterFormatDTO.setAddUserTeamList(userTeamAddList);
        teamAfterFormatDTO.setDelUserTeamList(userTeamDeleteList);
        teamAfterFormatDTO.setUpdateUserToMainTeamList(updateUserToMainTeamList);
        teamAfterFormatDTO.setUpdateUserToCoTeamList(updateUserToCoTeamList);
        teamAfterFormatDTO.setUpdateUserTeamMainList(updateUserTeamMainList);
        return teamAfterFormatDTO;
    }

    protected List<UserTeamEntity> getUserTeamListByParams(List<Long> dataIdList,  Integer businessType, Map<String, Object> map) {
        return new ArrayList<>();
    }

    /**
     *
     *
     * 获取最新的map,主要到这一步有dataId了，所以用dataId替换空的key
     * 之所以需要有返回值是因为老哥那边
     *
     * @param map
     */
    private Integer getLatestMap(Map<String, Set<String>> map, Long dataId, Integer updateLine) {
        if (Objects.nonNull(map)) {
            String key = null;
            Set<String> value = null;
            for (Map.Entry<String, Set<String>> entry : map.entrySet()) {
                key = entry.getKey();
                value = entry.getValue();
            }
            map.remove(key);
            map.put(String.valueOf(dataId), value);
            if (CollectionsUtil.isNotEmpty(value) && Objects.equals(updateLine, BasicConstant.ZERO)) {
                updateLine = BasicConstant.ONE;
            }
        }
        return updateLine;
    }

    /**
     * 这个方法是从TeamDataHelp.save方法拆出来的，为啥要拆？
     * （1）详情页团队新增成员的时候是不需要考虑审批情况，所以校验、保存是可以放在一套的
     * （2）从我们主业务的新增、编辑进行团队成员的新增、删除的时候，需要清晰的拆分出beforeSave->save->afterSave
     *
     * @param teamAfterVerifyDTO
     * @throws XbbException
     */
    public void businessSave(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {
        teamAfterVerifyDTO = specialVerify(teamAfterVerifyDTO);

        // 团队保存
        save(teamAfterVerifyDTO);
        //如果是工作流的话就不需要走下面步骤
        TeamSaveMiddlePojo teamSaveMiddlePojo = teamAfterVerifyDTO.getTeamSaveMiddlePojo();
        if (Objects.isNull(teamSaveMiddlePojo) || Objects.equals(teamSaveMiddlePojo.getWorkFlowTag(), false)) {
            // 后续默认业务处理
//            if (Objects.equals(teamAfterVerifyDTO.getFromDetail(), true)) {
            if (!Objects.equals(teamAfterVerifyDTO.getIsImport(), BasicConstant.ONE)) {
                afterSave(teamAfterVerifyDTO);
            }
//            }
            // 日志/消息（异步）
            if (!Objects.equals(teamAfterVerifyDTO.getIsImport(), BasicConstant.ONE)) {
                //只有非导入才会记录日志
                log(teamAfterVerifyDTO);
            }

            // 团队继承逻辑
            inheritanceSave(teamAfterVerifyDTO);

            // 动态
            dynamic(teamAfterVerifyDTO);
        }


    }
    /**
     * 团队详情tab栏信息
     *
     * @return
     */
    @Override
    public TeamDetailVO detail(TeamDetailDTO teamDetailDTO) throws XbbException {
        try {
            //表单共享标识，true：共享  false：隔离
            boolean formShareTag = true;
            Integer saasMark = teamDetailDTO.getSaasMark();
            Integer businessType = teamDetailDTO.getBusinessType();
            // 首先进行当前表单模式判断
            if (Objects.equals(SaasMarkEnum.PAAS.getCode(), saasMark)) {
                formShareTag = true;
            } else {
                String corpid = teamDetailDTO.getCorpid();
                Long formId = teamDetailDTO.getFormId();
                formShareTag = userTeamHelp.getFormShareTag(corpid, formId, businessType);
            }
            //非这两个业务以及经销商业务永远都是共享模式
            Integer distributorMark = teamDetailDTO.getDistributorMark();
            boolean businessTag = Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode());
            if ((Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode())) || !businessTag) {
                formShareTag = true;
            }
            Integer formShareTagValue = formShareTag ? FormPatternEnum.FORM_SHARE.getModel() : FormPatternEnum.FORM_ISOLATION.getModel();
            if (formShareTag) {
                //共享走共享的逻辑
                TeamDetailShareVO teamDetailShareVO = formShareDetail(teamDetailDTO, formShareTagValue);
                return teamDetailShareVO;
            } else {
                //隔离模式下如果非客户、线索的详情其实走的也是共享模式下的详情渲染
                TeamDetailIsolationVO teamDetailIsolationVO = formIsolationDetail(teamDetailDTO, formShareTagValue);
                return teamDetailIsolationVO;
            }
        } catch (XbbException e) {
            LOG.error("com.xbongbong.parent.abstracts.AbstractParentTeamStrategy.detail fail", e);
            throw e;
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }



    /**
     * 共享模式下详情tab的团队信息返回
     *
     * @param teamDetailDTO 详情传参
     * @param formShareTagValue 共享标识 0:共享  1:隔离
     * @return
     */
    public TeamDetailShareVO formShareDetail(TeamDetailDTO teamDetailDTO, Integer formShareTagValue) throws XbbException {
        TeamDetailShareVO teamDetailShareVO = new TeamDetailShareVO();
        Long dataId = teamDetailDTO.getDataId();
        String corpid = teamDetailDTO.getCorpid();
        Integer businessType = teamDetailDTO.getBusinessType();
        //查询团队用户信息 由子类实现
        List<UserTeamEntity> userTeamEntities = getUserTeamList(Arrays.asList(dataId), corpid, businessType, Boolean.FALSE, null);
        Map<String, UserTeamEntity> userTeamEntityMap = new HashMap<>(userTeamEntities.size() * 2);
        if (CollectionsUtil.isNotEmpty(userTeamEntities)) {
            userTeamEntityMap = userTeamEntities.stream().collect(Collectors.toMap(UserTeamEntity:: getUserId, a -> a, (k1, k2) -> k1));;
        }

        String explains;
        List<FieldAttrEntity> explainList;
        if(Objects.equals(teamDetailDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())){
            WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getByFormId(teamDetailDTO.getFormId(), corpid);
            if ( Objects.isNull(workOrderExplainEntity) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            explains = workOrderExplainEntity.getExplains();
            explainList = JsonHelperUtil.parseArray(explains, FieldAttrEntity.class);
        }else{
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(teamDetailDTO.getFormId(), teamDetailDTO.getCorpid());
            if ( Objects.isNull(paasFormExplainEntity) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            explains = paasFormExplainEntity.getExplains();
            explainList = JsonHelperUtil.parseArray(explains, FieldAttrEntity.class);
        }
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explains, null);
        //根据套餐判断负责人属性,用于前端判断负责人弹框单选、多选的判断
        Integer feeType = commonHelp.getCurrentCompanyPackage(teamDetailDTO.getCorpid());
        boolean ultimateTag = Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType());
        Integer multiple = null;
        if(!ultimateTag && FormOwnerUniqueEnum.getDefaultBusinessList().contains(businessType)){
            //只有旗舰版支持负责人唯一设置，其他版本拿默认设置
            FormOwnerUniqueEnum formOwnerUniqueEnum = FormOwnerUniqueEnum.getFormOwnerUniqueByBus(businessType);
            multiple = formOwnerUniqueEnum.getValue();
        }else{
            for (FieldAttrEntity fieldAttrEntity : explainList) {
                if(Objects.equals(fieldAttrEntity.getAttr(), FieldTypeEnum.OWNERID.getAlias())){
                    multiple = fieldAttrEntity.getMultiple();
                }
            }
        }
        //查询团队用户标签信息
        Map<String, List<UserLabelPojo>> userLabelPojoList = packageUserLabelInfo(teamDetailDTO, userTeamEntities);
        //获取用户相关信息
        packageUserInfo(teamDetailDTO, userTeamEntities, userLabelPojoList, teamDetailShareVO, explainMap);
        //查询当前登录人拥有哪些对团队相关操作权限
        ShareUserPermissionPojo shareUserPermissionPojo = packageUserPermissionInfo(teamDetailDTO, teamDetailShareVO, userTeamEntityMap, explainMap, ultimateTag);
        //封装整体需要返回的内容
        teamDetailShareVO.setModel(formShareTagValue);
        teamDetailShareVO.setUserPermissionPojo(shareUserPermissionPojo);
        teamDetailShareVO.setMultiple(multiple);
        return teamDetailShareVO;
    }

    /**
     * 子类实现
     * @param dataIdList
     * @param corpid
     * @param businessType
     * @param isPublic
     * @param isMain
     * @return
     */
    protected List<UserTeamEntity> getUserTeamList(Collection<Long> dataIdList, String corpid, Integer businessType, Boolean isPublic, Integer isMain) {
        return new ArrayList<>();
    }

    protected List<UserTeamEntity> getUserTeamListAndDel(List<Long> dataIdList, String corpid, Integer businessType, Boolean isPublic, Integer del) {
        return new ArrayList<>();
    }
    /**
     * 封装用户数据权限信息
     * (1)添加负责人： 表单中有负责人字段新增权限人员
     *         工单：没有限制哪些人能新增、删除负责人
     *         其他业务根据字段权限去过滤
     * (2)删除负责人： 有负责人字段删除权限人员
     *
     * (3)添加协同人：根据协同人字段权限去过滤
     *
     * (4)删除协同人：根据协同人字段权限去过滤
     *
     * (5)标签编辑权限：有表单编辑权限人员
     *
     * (6)负责人移交
     *      a:同时拥有负责人字段新增/删除权限
     *      b:负责人唯一表单：没有删除按钮，只有移交
     *      c:多负责人时，只支持移动端对单条数据某个成员移交
     *
     * @param teamDetailDTO
     * @param teamDetailShareVO 共享模式下返回实体
     * @return
     */
    private ShareUserPermissionPojo packageUserPermissionInfo(TeamDetailDTO teamDetailDTO, TeamDetailShareVO teamDetailShareVO,
                                                              Map<String, UserTeamEntity> userTeamEntityMap, Map<String, FieldAttrEntity> explainMap, boolean ultimateTag) throws XbbException {
        ShareUserPermissionPojo shareUserPermissionPojo = new ShareUserPermissionPojo(true, true, true, true, true,
                true, true);
        UserVO loginUser = teamDetailDTO.getLoginUser();
        Long dataId = teamDetailDTO.getDataId();
        String corpid = teamDetailDTO.getCorpid();
        // 由子类实现
        PaasFormDataEntityExt paasFormDataEntityExt = getData(corpid, teamDetailDTO.getBusinessType(), teamDetailDTO.getSaasMark(), dataId);
        // 改为由子类实现
        Boolean permission = !checkPermission(paasFormDataEntityExt, teamDetailDTO.getSaasMark(), loginUser, teamDetailDTO.getBusinessType(), teamDetailDTO.getMenuId(), corpid);

        if (Objects.isNull(paasFormDataEntityExt)) {
            shareUserPermissionPojo = new ShareUserPermissionPojo(false, false, false, false, false,
                    false, false);
            return shareUserPermissionPojo;
        }
        if (permission) {
            shareUserPermissionPojo = new ShareUserPermissionPojo(false, false, false, false, false,
                    false, false);
            return shareUserPermissionPojo;
        }
        Integer businessType = teamDetailDTO.getBusinessType();
        FieldAttrEntity ownerFieldAttr = explainMap.get(FieldTypeEnum.OWNERID.getAlias());
        FieldAttrEntity coUserFieldAttr = explainMap.get(FieldTypeEnum.COUSERID.getAlias());
        HandlerExplainDTO handlerExplainDTO = getSearchUserFieldPerCondtion(teamDetailDTO, paasFormDataEntityExt) ;
        TeamRelatedPojo teamRelatedPojo = new TeamRelatedPojo();
        UserTeamEntity userTeamEntity = userTeamEntityMap.get(teamDetailDTO.getUserId());
        boolean basicFormEdit = getBasicFormEdit(teamDetailDTO);
        teamRelatedPojo.setBasicFormEdit(basicFormEdit);
        //获取用户的共享权限规则是否有当前数据的编辑权
        VerifyUpdatePermissionDTO verifyUpdatePermissionDTO = new VerifyUpdatePermissionDTO(loginUser, paasFormDataEntityExt);
        boolean sharePermissionFlag = sharePermissionHelp.verifySharePermission4EditWithRuleEngine(verifyUpdatePermissionDTO);
        boolean shareCoAndHistoryCoEdit = getShareCoEditPer(teamDetailDTO, userTeamEntity, teamRelatedPojo, userTeamEntityMap.keySet());
        teamRelatedPojo.setShareCoAndHistoryCoEdit(shareCoAndHistoryCoEdit || sharePermissionFlag);
        //判断负责人、协同人新增、删除权限
        packageMainAndCoPermission(teamDetailDTO, businessType, ownerFieldAttr, coUserFieldAttr, handlerExplainDTO, shareUserPermissionPojo, teamDetailShareVO, teamRelatedPojo);
        if (Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())) {
            shareUserPermissionPojo.setEditCoFormPermission(false);
            shareUserPermissionPojo.setEditLabel(false);
            shareUserPermissionPojo.setChangeMain(false);
        }else if(Objects.equals(businessType, XbbRefTypeEnum.WAREHOUSE.getCode())) {
            shareUserPermissionPojo.setEditCoFormPermission(false);
            shareUserPermissionPojo.setEditLabel(false);
            boolean basicHandleOver = getBasicHandleOver(teamDetailDTO);
            shareUserPermissionPojo.setChangeMain(basicHandleOver);
        }else {
            boolean basicHandleOver = getBasicHandleOver(teamDetailDTO);
            teamRelatedPojo.setBasicHandleOver(basicHandleOver);
            //是否能修改协同人编辑权限,工单业务没这个权限
            //如果当前业务表单模板那边的那边协同人字段的表单权限为可读，那么就不能改成可编辑
            packageEditCoFormPermission(shareUserPermissionPojo, teamRelatedPojo, teamDetailDTO, coUserFieldAttr);
            //标签编辑权限
            packageShareEditLabelPermission(shareUserPermissionPojo, teamRelatedPojo, corpid, teamDetailDTO.getDistributorMark());
            //负责人移交权限、以及负责人新增权限
            packageChangeMain(teamDetailDTO, shareUserPermissionPojo, explainMap, teamRelatedPojo, teamDetailShareVO, userTeamEntity, ownerFieldAttr);
        }
        //根据套餐判断负责人属性
        if(!ultimateTag && FormOwnerUniqueEnum.getDefaultBusinessList().contains(businessType)){
            //只有旗舰版支持负责人唯一设置，其他版本拿默认设置，
            FormOwnerUniqueEnum formOwnerUniqueEnum = FormOwnerUniqueEnum.getFormOwnerUniqueByBus(businessType);
            Integer multiple = formOwnerUniqueEnum.getValue();
            //负责人唯一的时候，如果团队负责人不为空，去掉添加负责人开关
            Set<UserTeamEntity> mainSet = userTeamEntityMap.values().stream().filter(v -> Objects.equals(v.getIsMain(), Constant.ONE)).collect(Collectors.toSet());
            boolean hasMain = CollectionUtils.isNotEmpty(mainSet);
            if(Objects.equals(multiple,Constant.ZERO) && hasMain){
                shareUserPermissionPojo.setMainAdd(false);
            }
        }
        return shareUserPermissionPojo;

    }





    /**
     * 封装移交负责人和新增负责人的权限
     *    a:同时拥有负责人字段新增/删除权限
     *    b:web端共享模式只有表单模式设置负责人唯一并且当前数据负责人只有一个那么才有移交按钮，否则只有删除按钮。web隔离模式只有移交按钮没有删除按钮。
     *    c:移动端共享模式下只有表单模式设置负责人唯一并且当前数据只有一个负责人才显示移交按钮，否则同时同时显示删除和移交按钮。移动端隔离模式下只有移交按钮没有删除按钮。
     *
     * @param teamDetailDTO 入参实体
     * @param shareUserPermissionPojo 返回的实体
     * @param explainMap 表单解释
     * @param teamRelatedPojo 表单解释
     * @param teamDetailShareVO 人员返回实体
     */
    private void packageChangeMain(TeamDetailDTO teamDetailDTO, ShareUserPermissionPojo shareUserPermissionPojo,
                                   Map<String, FieldAttrEntity> explainMap, TeamRelatedPojo teamRelatedPojo, TeamDetailShareVO teamDetailShareVO,
                                   UserTeamEntity userTeamEntity, FieldAttrEntity ownerFieldAttr) throws XbbException {
        String platform = teamDetailDTO.getPlatform();
        Integer businessType = teamDetailDTO.getBusinessType();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(teamDetailDTO.getLoginUser(), userEntity);
        Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.getByCode(teamDetailDTO.getSaasMark()), teamDetailDTO.getBusinessType(), teamDetailDTO.getMenuId());
        List<MainUserPojo> mainUserArr = teamDetailShareVO.getMainUserArr();
        FieldAttrEntity fieldAttrEntity = explainMap.get(FieldTypeEnum.OWNERID.getAlias());
        Integer ownerTag = BasicConstant.ZERO;
        Integer multiple = fieldAttrEntity.getMultiple();
        Integer feeType = commonHelp.getCurrentCompanyPackage(teamDetailDTO.getCorpid());
        if (Objects.isNull(multiple) || !Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType())) {
            FormOwnerUniqueEnum formOwnerUniqueEnum = FormOwnerUniqueEnum.getFormOwnerUniqueByBus(businessType);
            ownerTag = formOwnerUniqueEnum.getValue();
        }else {
            ownerTag = multiple;
        }
        //有些业务，被上游影响，导致没有负责人的，就算是负责人唯一，也应该有新增权限
        if (Objects.equals(OwnerUniqueDefaultEnum.UNIQUE.getValue(), ownerTag) && CollectionsUtil.isNotEmpty(teamDetailShareVO.getMainUserArr())) {
            shareUserPermissionPojo.setMainAdd(false);
        }
        //判断有没有基础的移交权限,现在移交也需要判断这个人有没有编辑权限
        boolean basicHandleOver = teamRelatedPojo.getBasicHandleOver();
        Boolean shareCoAndHistoryCoEdit = teamRelatedPojo.getShareCoAndHistoryCoEdit();
        if (!basicHandleOver || !shareCoAndHistoryCoEdit) {
            shareUserPermissionPojo.setChangeMain(false);
            //这里还需要判断一下删除按钮，表单未设置负责人唯一 或者 表单设置负责人唯一，但是存在历史数据有多个负责人有删除按钮
            if (Objects.equals(ownerTag, OwnerUniqueDefaultEnum.UNIQUE.getValue()) &&
                    CollectionsUtil.isNotEmpty(mainUserArr) && mainUserArr.size() == BasicConstant.ONE) {
                shareUserPermissionPojo.setMainDel(false);
            }
            return;
        }
        if (Objects.equals(platform, PlatFormEnum.WEB.getValue())) {
            if (Objects.equals(ownerTag, OwnerUniqueDefaultEnum.UNIQUE.getValue()) &&
                    CollectionsUtil.isNotEmpty(mainUserArr) && mainUserArr.size() == BasicConstant.ONE) {
                //web端联系人移交按钮跟删除按钮是可能同时存在，其它业务在web端移交按钮跟删除按钮是不可能同时存在的
                if (Objects.equals(XbbRefTypeEnum.CONTACT.getCode(), businessType)
                        && Objects.equals(BasicConstant.ZERO, ownerFieldAttr.getRequired())) {

                }else {
                    //这时候有移交按钮没有删除按钮
                    shareUserPermissionPojo.setMainDel(false);
                    return;
                }
            }else {
                //这时候没有移交按钮但是有删除按钮
                shareUserPermissionPojo.setChangeMain(false);
                return;
            }
        }else if (Objects.equals(platform, PlatFormEnum.DINGTALK.getValue())) {
            if (Objects.equals(ownerTag, OwnerUniqueDefaultEnum.UNIQUE.getValue())
                    && CollectionsUtil.isNotEmpty(mainUserArr) && mainUserArr.size() == BasicConstant.ONE) {
                //移动端端联系人移交按钮跟删除按钮是可能同时存在，其它业务在web端移交按钮跟删除按钮是不可能同时存在的
                if (Objects.equals(XbbRefTypeEnum.CONTACT.getCode(), businessType)
                        && Objects.equals(BasicConstant.ZERO, ownerFieldAttr.getRequired())) {

                }else {
                    //这时候只有移交按钮没有删除按钮
                    shareUserPermissionPojo.setMainDel(false);
                    return;
                }
            }
        }
    }


    /**
     * 共享模式下获取标签编辑的权限
     *
     * @param shareUserPermissionPojo 权限实体
     * @param teamRelatedPojo 中间流转参数实体
     * @param corpid 公司id
     * @param distributorMark 经销商标识 1：经销商 0：非经销商
     * @return
     */
    private void packageShareEditLabelPermission(ShareUserPermissionPojo shareUserPermissionPojo, TeamRelatedPojo teamRelatedPojo, String corpid, Integer distributorMark) throws XbbException {
        if (Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(), distributorMark)) {
            shareUserPermissionPojo.setEditLabel(false);
            return;
        }
        Integer feeType = commonHelp.getCurrentCompanyPackage(corpid);
        if (!Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType())) {
            //非旗舰版套餐，是没有编辑标签的权限的
            shareUserPermissionPojo.setEditLabel(false);
        } else {
            boolean eidtLabelPermission = teamRelatedPojo.getShareCoAndHistoryCoEdit();
            shareUserPermissionPojo.setEditLabel(eidtLabelPermission);
        }
    }


    /**
     * 封装协同人权限编辑按钮权限
     *  1. 可操作人员：有表单编辑权限人员
     *  2. 若表单协同人默认权限为只读，此时无法调整
     *
     * @param shareUserPermissionPojo 权限实体
     * @param teamRelatedPojo 放置一些流转需要用到的参数
     * @param coUserFieldAttr 协同人字段
     *
     */
    private void packageEditCoFormPermission(ShareUserPermissionPojo shareUserPermissionPojo, TeamRelatedPojo teamRelatedPojo,
                                             TeamDetailDTO teamDetailDTO, FieldAttrEntity coUserFieldAttr) throws XbbException {
        Integer distributorMark = teamDetailDTO.getDistributorMark();
        String corpid = teamDetailDTO.getCorpid();
        if (Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(), distributorMark)) {
            shareUserPermissionPojo.setEditCoFormPermission(false);
            return;
        }
        Integer feeType = commonHelp.getCurrentCompanyPackage(corpid);
        if (!Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType())) {
            shareUserPermissionPojo.setEditCoFormPermission(false);
            return;
        }
        /*//表单设计那边对可编辑的影响
        Integer feeType = commonHelp.getCurrentCompanyPackage(corpid);
        Integer formPermission = coUserFieldAttr.getFormPermission();
        //如果套餐是旗舰版就按照表单设置那边走，如果套餐是非旗舰版的就按照默认规则走
        if (!Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType())) {
            FormCoUserDefaultPermissionEnum formCoUserDefaultPermissionEnum = FormCoUserDefaultPermissionEnum.getFormPatternEnumByBus(businessType);
            formPermission = formCoUserDefaultPermissionEnum.getDefaultPermissionValue();
        } else {
            if (Objects.isNull(formPermission)) {
                FormCoUserDefaultPermissionEnum formCoUserDefaultPermissionEnum = FormCoUserDefaultPermissionEnum.getFormPatternEnumByBus(businessType);
                formPermission = formCoUserDefaultPermissionEnum.getDefaultPermissionValue();
            }
        }
        if (Objects.equals(formPermission, CoUserPermissionEnum.READ.getPermissionValue())) {
            shareUserPermissionPojo.setEditCoFormPermission(false);
            return;
        }*/
        boolean eidtCoFormPermission = teamRelatedPojo.getShareCoAndHistoryCoEdit();
        shareUserPermissionPojo.setEditCoFormPermission(eidtCoFormPermission);
    }

    /**
     * 封装负责人新增和删除权限
     *
     * @param teamDetailDTO 详情入参实体
     * @param businessType 业务类型
     * @param ownerFieldAttr 负责人字段
     * @param coUserFieldAttr 协同人字段
     * @param handlerExplainDTO 用于下面进行判断权限的实体
     */
    private void packageMainAndCoPermission(TeamDetailDTO teamDetailDTO,Integer businessType, FieldAttrEntity ownerFieldAttr,
                                            FieldAttrEntity coUserFieldAttr, HandlerExplainDTO handlerExplainDTO, ShareUserPermissionPojo shareUserPermissionPojo,
                                            TeamDetailShareVO teamDetailShareVO, TeamRelatedPojo teamRelatedPojo) throws XbbException {
        UserVO loginUser = teamDetailDTO.getLoginUser();
        Map<String, TeamUserPojo> coUserMap = new HashMap<>();
        List<String> ownerIdList = new ArrayList<>();
        if (CollectionsUtil.isNotEmpty(teamDetailShareVO.getMainUserArr())) {
            teamDetailShareVO.getMainUserArr().forEach(mainUserPojo -> {
                ownerIdList.add(mainUserPojo.getTeamUserPojo().getUserId());
            });
            handlerExplainDTO.setOwnerId(ownerIdList);
        }
        List<String> coUserIdList = new ArrayList<>();
        if (CollectionsUtil.isNotEmpty(teamDetailShareVO.getCoopUserArr())) {
            teamDetailShareVO.getCoopUserArr().forEach(coopUserPojo -> {
                String coUserId = coopUserPojo.getTeamUserPojo().getUserId();
                coUserIdList.add(coUserId);
                coUserMap.put(coUserId, coopUserPojo.getTeamUserPojo());
            });
            handlerExplainDTO.setCoUserId(coUserIdList);
        }
        if (Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())) {
            if (Objects.equals(teamRelatedPojo.getBasicFormEdit(), false)) {
                shareUserPermissionPojo.setCoAdd(false);
                shareUserPermissionPojo.setCoDel(false);
            }else {
                Boolean haveCoUserAddPermission = ExplainUtil.advancedOperationHavePermission(coUserFieldAttr, handlerExplainDTO, FieldAdvanceOperationEnum.ADD.getOperation());
                Boolean haveCoUserDelPermission = ExplainUtil.advancedOperationHavePermission(coUserFieldAttr, handlerExplainDTO, FieldAdvanceOperationEnum.DEL.getOperation());
                //高级权限校验
                shareUserPermissionPojo.setCoAdd(haveCoUserAddPermission);
                shareUserPermissionPojo.setCoDel(haveCoUserDelPermission);
            }
            shareUserPermissionPojo.setMainAdd(false);
            shareUserPermissionPojo.setMainDel(false);
        } else if (Objects.equals(businessType, XbbRefTypeEnum.WAREHOUSE.getCode())) {
            shareUserPermissionPojo.setMainAdd(true);
            shareUserPermissionPojo.setMainDel(true);
            shareUserPermissionPojo.setCoAdd(false);
            shareUserPermissionPojo.setCoDel(false);
        }else {
            if (Objects.nonNull(ownerFieldAttr)) {
                Boolean haveMainAddPermission = ExplainUtil.advancedOperationHavePermission(ownerFieldAttr, handlerExplainDTO, FieldAdvanceOperationEnum.ADD.getOperation());
                Boolean haveMainDelPermission = ExplainUtil.advancedOperationHavePermission(ownerFieldAttr, handlerExplainDTO, FieldAdvanceOperationEnum.DEL.getOperation());
                UserEntity userEntity = new UserEntity();
                BeanUtil.copyProperties(loginUser, userEntity);
                if (teamRelatedPojo.getShareCoAndHistoryCoEdit()) {
                    //高级权限校验
                    shareUserPermissionPojo.setMainAdd(haveMainAddPermission);
                    shareUserPermissionPojo.setMainDel(haveMainDelPermission);
                }else {
                    shareUserPermissionPojo.setMainAdd(false);
                    shareUserPermissionPojo.setMainDel(false);
                }
            }
            if (Objects.nonNull(coUserFieldAttr)) {
                Boolean haveCoUserAddPermission = ExplainUtil.advancedOperationHavePermission(coUserFieldAttr, handlerExplainDTO, FieldAdvanceOperationEnum.ADD.getOperation());
                Boolean haveCoUserDelPermission = ExplainUtil.advancedOperationHavePermission(coUserFieldAttr, handlerExplainDTO, FieldAdvanceOperationEnum.DEL.getOperation());
                if (teamRelatedPojo.getShareCoAndHistoryCoEdit()) {
                    //高级权限校验
                    shareUserPermissionPojo.setCoAdd(haveCoUserAddPermission);
                    shareUserPermissionPojo.setCoDel(haveCoUserDelPermission);
                }else {
                    shareUserPermissionPojo.setCoAdd(false);
                    shareUserPermissionPojo.setCoDel(false);
                }
            }
        }
    }

    /**
     * 获取最基础的表单权限
     *
     * @param teamDetailDTO 团队详情入参
     * @return
     */
    private boolean getBasicFormEdit(TeamDetailDTO teamDetailDTO) throws XbbException {
        Integer saasMark = teamDetailDTO.getSaasMark();
        String corpid = teamDetailDTO.getCorpid();
        Long appId = teamDetailDTO.getAppId();
        Long menuId = teamDetailDTO.getMenuId();
        Integer businessType = teamDetailDTO.getBusinessType();
        UserVO loginUser = teamDetailDTO.getLoginUser();
        String userId = teamDetailDTO.getUserId();
        //paas表单的编辑权限判断
        if (Objects.equals(SaasMarkEnum.PAAS.getCode(), saasMark)) {
            if(Objects.isNull(appId) || Objects.isNull(menuId)){
                Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                params.put(StringConstant.CORPID,corpid);
                params.put(StringConstant.FORM_ID,teamDetailDTO.getFormId());
                params.put(StringConstant.DEL, DelEnum.NORMAL);
                //前端没有传
                List<PaasFormEntityExt> paasFormEntityExts = paasFormModel.findEntitys(params);
                if(Objects.nonNull(paasFormEntityExts)){
                    PaasFormEntityExt paasFormEntityExt = paasFormEntityExts.get(Constant.ZERO);
                    appId = paasFormEntityExt.getAppId();
                    menuId = paasFormEntityExt.getMenuId();
                    teamDetailDTO.setAppId(appId);
                    teamDetailDTO.setMenuId(menuId);
                }
            }
            UserFormPermissionVO userFormPermissionInternal =  userModel.getUserFormPermission(corpid, userId, appId, menuId);
            PermissionTermsPojo permission = userFormPermissionInternal.getFormPermission().getPermission();
            Boolean isAdmin = userFormPermissionInternal.getIsAdminOrBoss();
            if (Objects.equals(BasicConstant.ZERO, permission.getUpdate()) && !isAdmin) {
                return false;
            }
        }else {
            //下面是saas表单的编辑权限判断
            UpdateProPermissionAliasEnum updateProPermissionAliasEnum = UpdateProPermissionAliasEnum.getByCode(businessType);
            if (Objects.equals(saasMark, SaasMarkEnum.SAAS.getCode()) && !loginUser.getPermSet().contains(updateProPermissionAliasEnum.getAlias())) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取查询负责人、协同人字段权限的条件
     *
     * @return
     */
    private HandlerExplainDTO getSearchUserFieldPerCondtion(TeamDetailDTO teamDetailDTO, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        UserVO loginUser = teamDetailDTO.getLoginUser();
        Integer businessType = teamDetailDTO.getBusinessType();

        UserEntity userEntity = new UserEntity();
        packageUserEntity(userEntity, loginUser);
        List<String> subIdList = userModel.getManageUser(userEntity);
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO(paasFormDataEntityExt.getCreatorId(), new ArrayList<>(),
                new ArrayList<>(), subIdList, loginUser.getUserId(), loginUser);
        handlerExplainDTO.setBusinessType(businessType);
        return handlerExplainDTO;
    }



    /**
     * 封装用户信息，改掉原先直接BeanCopy的方式,用到哪些参数塞哪些参数
     *
     * @param userEntity
     * @param loginUser
     */
    private void packageUserEntity(UserEntity userEntity, UserVO loginUser) {
        userEntity.setCorpid(loginUser.getCorpid());
        userEntity.setRoleIds(loginUser.getRoleIds());
        userEntity.setUserId(loginUser.getUserId());
        userEntity.setIsLeaderInDepts(loginUser.getIsLeaderInDepts());
    }



    /**
     * 获取共享模式下用户的相关信息
     *
     * @param teamDetailDTO 团队详情入参实体
     * @param userTeamEntities 用户信息
     * @param userLabelPojoList 用户标签
     * @param teamDetailShareVO 共享模式下返回实体
     */
    private void packageUserInfo(TeamDetailDTO teamDetailDTO, List<UserTeamEntity> userTeamEntities, Map<String, List<UserLabelPojo>> userLabelPojoList, TeamDetailShareVO teamDetailShareVO,
                                 Map<String, FieldAttrEntity> explainMap) throws XbbException {
        Integer businessType = teamDetailDTO.getBusinessType();
        String corpid = teamDetailDTO.getCorpid();
        List<MainUserPojo> mainUserArr = new ArrayList<>();
        List<CoopUserPojo> coopUserArr = new ArrayList();
        Integer feeType = commonHelp.getCurrentCompanyPackage(corpid);
        boolean ultimateTag = Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType());
        Integer formSetFormPermission = TeamMembersConstant.NO_FORM_PERMISSION;
        //工单是没有任何标签、协同人可编辑权限、新增负责人、删除负责人功能等等；仓库没有任何标签、协同人可编辑权限
        boolean specialBusTag = Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.WAREHOUSE.getCode());
        if (!specialBusTag) {
            //获取表单解释里面的协同人字段可编辑权限值
            formSetFormPermission = getFormSetFormPermission(teamDetailDTO);
        }
        //--------------------------
        if (CollectionsUtil.isNotEmpty(userTeamEntities)) {
            List<String> userIds = new ArrayList<>();
            userTeamEntities.forEach(userTeamEntity -> {
                userIds.add(userTeamEntity.getUserId());
            });
            Map<String, UserEntity> userMap = userModel.getUserEntityMap(corpid,userIds,BasicConstant.ZERO);
            List<UserLabelPojo> userLabelPojos = new ArrayList<>();
            Iterator<UserTeamEntity> userTeamEntityIterator = userTeamEntities.iterator();
            while (userTeamEntityIterator.hasNext()) {
                UserTeamEntity userTeamEntity = userTeamEntityIterator.next();
                String userId = userTeamEntity.getUserId();
                UserEntity userEntity = userMap.get(userId);
                if (Objects.isNull(userEntity)) {
                    userTeamEntityIterator.remove();
                    continue;
                }
                if (ultimateTag && !specialBusTag) {
                    userLabelPojos = userLabelPojoList.get(userId);
                }
                //formPermission字段还需要处理一下，如果为空需要去读取默认值;工单业务因为不显示协同人可编辑选项，所以这边返回-1
                Integer formPermission = userTeamEntity.getFormPermission();
                if (specialBusTag || !ultimateTag) {
                    formPermission = TeamMembersConstant.NO_FORM_PERMISSION;
                }else if (Objects.isNull(formPermission)) {
                    formPermission = FormCoUserDefaultPermissionEnum.getDefaultPerByBus(businessType);
                }
                TeamUserPojo teamUserPojo = new TeamUserPojo(userTeamEntity.getId(), userTeamEntity.getUserId(), userEntity.getName(),
                        userEntity.getAvatar(), formPermission, formSetFormPermission,userEntity.getDel());
                //负责人
                if (Objects.equals(BasicConstant.ONE, userTeamEntity.getIsMain())) {
                    MainUserPojo mainUserPojo = new MainUserPojo();
                    mainUserPojo.setTeamUserPojo(teamUserPojo);
                    mainUserPojo.setLabels(userLabelPojos);
                    mainUserArr.add(mainUserPojo);
                }else {
                    //协同人
                    CoopUserPojo coopUserPojo = new CoopUserPojo();
                    coopUserPojo.setTeamUserPojo(teamUserPojo);
                    coopUserPojo.setLabels(userLabelPojos);
                    coopUserArr.add(coopUserPojo);
                }
            }
        }
        teamDetailShareVO.setMainUserArr(mainUserArr);
        teamDetailShareVO.setCoopUserArr(coopUserArr);
        //仓库业务需要隐藏掉协同人tab栏；以及paas表单没有协同人字段的
        if (Objects.equals(XbbRefTypeEnum.WAREHOUSE.getCode(), businessType)) {
            teamDetailShareVO.setNoCoUserTab(true);
        }
    }

    /**
     * 获取表单设置里面的协同人可编辑权限
     *
     * @param teamDetailDTO
     * @return
     */
    private Integer getFormSetFormPermission(TeamDetailDTO teamDetailDTO) throws XbbException {
        PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(teamDetailDTO.getCorpid(), teamDetailDTO.getFormId(), teamDetailDTO.getBusinessType());
        String explains = paasFormExplainEntity.getExplains();
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explains, null);
        FieldAttrEntity fieldAttrEntity = explainMap.get(FieldTypeEnum.COUSERID.getAlias());
        Integer formSetFormPermission = fieldAttrEntity.getFormPermission();
        if (Objects.isNull(formSetFormPermission)) {
            formSetFormPermission = FormCoUserDefaultPermissionEnum.getDefaultPerByBus(teamDetailDTO.getBusinessType());
        }
        return formSetFormPermission;
    }





    /**
     * 隔离模式下详情tab的团队信息返回
     *
     * @param teamDetailDTO 团队详情的入参实体
     * @param formShareTagValue 0：共享 1：隔离
     * @return
     */
    private TeamDetailIsolationVO formIsolationDetail(TeamDetailDTO teamDetailDTO, Integer formShareTagValue) throws XbbException{
        Long dataId = teamDetailDTO.getDataId();
        String corpid = teamDetailDTO.getCorpid();
        Integer businessType = teamDetailDTO.getBusinessType();
        //查询团队用户信息
        List<UserTeamEntity> userTeamEntities = userTeamHelp.getUserTeamList(Arrays.asList(dataId), corpid, businessType, Boolean.FALSE, null);
        //查询团队用户标签信息
        Map<String, List<UserLabelPojo>> userLabelPojoList = packageUserLabelInfo(teamDetailDTO, userTeamEntities);
        List<FieldAttrEntity> explainList;
        if(Objects.equals(teamDetailDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())){
            WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getByFormId(teamDetailDTO.getFormId(), corpid);
            if ( Objects.isNull(workOrderExplainEntity) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            explainList = JsonHelperUtil.parseArray(workOrderExplainEntity.getExplains(), FieldAttrEntity.class);
        }else{
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(teamDetailDTO.getFormId(), teamDetailDTO.getCorpid());
            if ( Objects.isNull(paasFormExplainEntity) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            explainList = JsonHelperUtil.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        }
        //根据套餐判断负责人属性,用于前端判断负责人弹框单选、多选的判断
        Integer feeType = commonHelp.getCurrentCompanyPackage(teamDetailDTO.getCorpid());
        boolean ultimateTag = Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType());
        Integer multiple = null;
        if(!ultimateTag && FormOwnerUniqueEnum.getDefaultBusinessList().contains(businessType)){
            //只有旗舰版支持负责人唯一设置，其他版本拿默认设置
            FormOwnerUniqueEnum formOwnerUniqueEnum = FormOwnerUniqueEnum.getFormOwnerUniqueByBus(businessType);
            multiple = formOwnerUniqueEnum.getValue();
        }else{
            for (FieldAttrEntity fieldAttrEntity : explainList) {
                if(Objects.equals(fieldAttrEntity.getAttr(),FieldTypeEnum.OWNERID.getAlias())){
                    multiple = fieldAttrEntity.getMultiple();
                }
            }
        }
        //封装整体需要返回的内容
        TeamDetailIsolationVO teamDetailIsolationVO = new TeamDetailIsolationVO();
        packageFormIsolationDetail(teamDetailDTO, userTeamEntities, userLabelPojoList, teamDetailIsolationVO, formShareTagValue);
        teamDetailIsolationVO.setMultiple(multiple);
        return teamDetailIsolationVO;
    }

    /**
     * 获取explainMap
     *
     * @param teamDetailDTO
     * @return
     */
    private Map<String, FieldAttrEntity> getExplainMap(TeamDetailDTO teamDetailDTO) throws XbbException {
        String corpid = teamDetailDTO.getCorpid();
        Integer businessType = teamDetailDTO.getBusinessType();
        Long formId = teamDetailDTO.getFormId();
        Map<String, FieldAttrEntity> explainMap = new HashMap<>();
        if (Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())) {
            WorkOrderExplainEntity explainEntity = workOrderExplainModel.getByFormId(formId, corpid);
            if (Objects.isNull(explainEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            explainMap = ExplainUtil.getExplainMap(explainEntity.getExplains(), null);
        }else {
            PaasFormExplainEntity explainEntity = paasFormExplainModel.getByFormId(formId, corpid);
            if (Objects.isNull(explainEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            explainMap = ExplainUtil.getExplainMap(explainEntity.getExplains(), null);
        }
        return explainMap;
    }

    /**
     * 隔离模式需要返回的信息
     *
     * @param teamDetailDTO 查询入参实体
     * @param userTeamEntities 用户信息
     * @param userLabelPojoMap 用表标签实体
     * @param teamDetailIsolationVO 返回的隔离实体
     * @param formShareTagValue  0：共享 1：隔离
     */
    private void packageFormIsolationDetail(TeamDetailDTO teamDetailDTO, List<UserTeamEntity> userTeamEntities, Map<String, List<UserLabelPojo>> userLabelPojoMap,
                                            TeamDetailIsolationVO teamDetailIsolationVO, Integer formShareTagValue) throws XbbException {
        Map<String, FieldAttrEntity> explainMap = getExplainMap(teamDetailDTO);
        FieldAttrEntity ownerFieldAttr =  explainMap.get(FieldTypeEnum.OWNERID.getAlias());
        FieldAttrEntity coUserFieldAttr = explainMap.get(FieldTypeEnum.COUSERID.getAlias());
        Integer businessType = teamDetailDTO.getBusinessType();
        String corpid = teamDetailDTO.getCorpid();
        UserVO loginUser = teamDetailDTO.getLoginUser();
        List<TeamGroupPojo> teamGroupPojoList = new ArrayList<>();
        HistoryCoInfoPojo historyCoInfoPojo = new HistoryCoInfoPojo();
        List<CoopUserPojo> independentCoopUserArr = new ArrayList<>();
        Set<String> historyCoopUserSet = new HashSet<>();
        Set<String> allTeamCoopUserSet = new HashSet<>();
        Set<String> allCouserSet = new HashSet<>();
        //先查询出有几个小团队
        Set<String> isolationOwnerSet = new HashSet<>();
        List<String> userIds = new ArrayList<>();
        Map<String, UserTeamEntity> userEntityMap = new HashMap<>();
        if (CollectionsUtil.isNotEmpty(userTeamEntities)) {
            userEntityMap = userTeamEntities.stream().collect(Collectors.toMap(UserTeamEntity:: getUserId, a -> a, (k1, k2) -> k1));
        }
        for (UserTeamEntity userTeamEntity : userTeamEntities) {
            if (Objects.equals(userTeamEntity.getIsMain(), BasicConstant.ONE)) {
                isolationOwnerSet.add(userTeamEntity.getUserId());
            }
            userIds.add(userTeamEntity.getUserId());
        }
        Map<String, UserEntity> userMap = userModel.getUserEntityMap(corpid,userIds,BasicConstant.ZERO);
        //权限前置处理
        TeamRelatedPojo teamRelatedPojo = new TeamRelatedPojo();
        boolean basicFormEdit = getBasicFormEdit(teamDetailDTO);
        boolean basicHandleOver = getBasicHandleOver(teamDetailDTO);
        teamRelatedPojo.setBasicFormEdit(basicFormEdit);
        teamRelatedPojo.setBasicHandleOver(basicHandleOver);
        //获取当前套餐版本
        Integer feeType = commonHelp.getCurrentCompanyPackage(corpid);
        //获取表单设计里面的协同人可编辑权限值（只读、可编辑）
        Integer formSetFormPermission = getFormSetFormPermission(teamDetailDTO);
        //获取有没有主数据的可查看数据权限
        PaasFormDataEntityExt paasFormDataEntityExt = getData(teamDetailDTO.getCorpid(), teamDetailDTO.getBusinessType(), teamDetailDTO.getSaasMark(), teamDetailDTO.getDataId());
        Boolean mainDataCheck = true;
        if (Objects.isNull(paasFormDataEntityExt)) {
            mainDataCheck = false;
        }
        if (mainDataCheck) {
            Boolean permission = !checkPermission(paasFormDataEntityExt, teamDetailDTO.getSaasMark(), loginUser, teamDetailDTO.getBusinessType(), teamDetailDTO.getMenuId(), teamDetailDTO.getCorpid());
            if (permission) {
                mainDataCheck = false;
            }
        }
        boolean ultimateTag = Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType());
        for (String userId : isolationOwnerSet) {
            TeamGroupPojo teamGroupPojo = new TeamGroupPojo();
            List<MainUserPojo> mainUserArr = new ArrayList<>();
            List<CoopUserPojo> coopUserArr = new ArrayList();
            Set<String> currentTeamCoopUserSet = new HashSet<>();
            Long id = BasicConstant.ZERO_LONG;
            String teamName = "";
            for (UserTeamEntity userTeamEntity : userTeamEntities) {
                Integer formPermission = userTeamEntity.getFormPermission();
                if (!ultimateTag) {
                    formPermission = TeamMembersConstant.NO_FORM_PERMISSION;;
                } else if (Objects.isNull(formPermission)) {
                    formPermission = FormCoUserDefaultPermissionEnum.getDefaultPerByBus(businessType);
                }
                UserEntity userEntity = userMap.get(userTeamEntity.getUserId());
                TeamUserPojo teamUserPojo = new TeamUserPojo(userTeamEntity.getId(), userTeamEntity.getUserId(), userEntity.getName(),
                        userEntity.getAvatar(), formPermission, formSetFormPermission, userEntity.getDel());
                List<UserLabelPojo> userLabelPojos = new ArrayList<>();
                //非旗舰版套餐，没有标签相关信息
                if (Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType())) {
                    userLabelPojos = userLabelPojoMap.get(userTeamEntity.getUserId());
                }
                if (Objects.equals(userId, userTeamEntity.getUserId())) {
                    MainUserPojo mainUserPojo = new MainUserPojo(teamUserPojo, userLabelPojos);
                    mainUserArr.add(mainUserPojo);
                    id = userTeamEntity.getId();
                    teamName = userTeamEntity.getName();
                    if (StringUtil.isEmpty(teamName)) {
                        teamName = String.format(I18nMessageUtil.getMessage(TeamMembersConstant.TEAM_DEFAULT_NAME), userTeamEntity.getUserName());
                    }
                } else if (Objects.equals(userId, userTeamEntity.getTeamUserId())) {
                    CoopUserPojo coopUserPojo = new CoopUserPojo(teamUserPojo, userLabelPojos);
                    coopUserArr.add(coopUserPojo);
                    currentTeamCoopUserSet.add(userTeamEntity.getUserId());
                    allTeamCoopUserSet.add(userTeamEntity.getUserId());
                    allCouserSet.add(userTeamEntity.getUserId());
                } else if (!isolationOwnerSet.contains(userTeamEntity.getUserId())) {
                    allCouserSet.add(userTeamEntity.getUserId());
                    //历史协同人 -> 最初就没有归属团队的协同人；还有现在的团队没有了负责人的协同人，都会被归类到历史协同人
                    if (!historyCoopUserSet.contains(userTeamEntity.getUserId())) {
                        historyCoopUserSet.add(userTeamEntity.getUserId());
                        CoopUserPojo coopUserPojo = new CoopUserPojo(teamUserPojo, userLabelPojos);
                        //这边是可能独立协同人的一个集合，真正最后结果需要下面最后过滤一波
                        independentCoopUserArr.add(coopUserPojo);
                    }
                }
            }
            teamGroupPojo.setId(id);
            teamGroupPojo.setName(teamName);
            teamGroupPojo.setMainUserArr(mainUserArr);
            teamGroupPojo.setCoopUserArr(coopUserArr);
            IsolationUserPermissionPojo isolationUserPermissionPojo = packageIsolationUserPermission(teamDetailDTO, teamGroupPojo, teamRelatedPojo, userEntityMap, ownerFieldAttr, coUserFieldAttr, currentTeamCoopUserSet, userId, isolationOwnerSet, mainDataCheck, paasFormDataEntityExt);
            teamGroupPojo.setUserPermissionPojo(isolationUserPermissionPojo);
            teamGroupPojoList.add(teamGroupPojo);
        }
        teamDetailIsolationVO.setModel(formShareTagValue);
        teamDetailIsolationVO.setTeamGroups(teamGroupPojoList);
        //封装协同人(历史协同人)的相关信息,independentCoopUserArr去除已经在团队里面的协同人，剩下的都是独立协同人
        if (CollectionsUtil.isNotEmpty(independentCoopUserArr)) {
            Iterator<CoopUserPojo> iterator = independentCoopUserArr.iterator();
            while (iterator.hasNext()) {
                CoopUserPojo coopUserPojo = iterator.next();
                if (isolationOwnerSet.contains(coopUserPojo.getTeamUserPojo().getUserId())
                        || allTeamCoopUserSet.contains(coopUserPojo.getTeamUserPojo().getUserId())) {
                    iterator.remove();
                }
            }
        }
        historyCoInfoPojo.setIndependentCoopUserArr(independentCoopUserArr);
        packageIsolationHistoryCoPer(teamDetailDTO, historyCoInfoPojo, teamDetailIsolationVO, userEntityMap, coUserFieldAttr, mainDataCheck,
                isolationOwnerSet, allCouserSet, teamRelatedPojo, paasFormDataEntityExt);
        //新增团队权限
        packageIsolationAddTeam(teamDetailDTO, teamDetailIsolationVO, isolationOwnerSet, allCouserSet, mainDataCheck, ultimateTag, teamRelatedPojo, paasFormDataEntityExt);
    }

    /**
     * 编辑协同人操作权限时候的日志
     *
     * @param loginUser 当前登录人
     * @param formId 表单id
     * @param userId 当前被操作对象的用户id
     * @param corpid 公司id
     * @param businessType 业务类型
     * @param object 不同业务的主数据实体
     * @param content 具体内容可编辑/不可编辑
     * @throws XbbException
     */
    public void saveUpdateCoPerLogger(UserVO loginUser, Long formId, String userId, String corpid, Integer businessType, Object object, String content, String httpHeader) throws XbbException {
        Runnable runnable = () -> {
            OperateModuleTypeEnum operateModuleTypeEnum = OperateModuleTypeEnum.RESPONSIBLE_TEAM;
            OperateTypeEnum operateTypeEnum = OperateTypeEnum.EDIT;
            UserEntity userEntity = userModel.getByKey(userId, corpid);
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(object, paasFormDataEntity);
            PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
            String message = I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_EDIT_COUSER_PER);
            String loginUserId = loginUser.getUserId();
            String userName = loginUser.getName();
            String formName = paasFormEntityExt.getName();
            try {
                String objectName = getSaveName(corpid, businessType, paasFormEntityExt, paasFormDataEntity);
                String operateObject = userEntity.getName();
                String memo = String.format(message, userName, formName, objectName, operateObject, content);
                mongoLogHelp.buildLogWithoutAsync(corpid, loginUserId, userName, operateModuleTypeEnum, operateTypeEnum,
                        userEntity.getUserId(), operateObject, memo, httpHeader);
            } catch (XbbException e){
                LOG.error("com.xbongbong.paas.service.team.strategy.AbstractTeamStrategy.saveUpdateCoPerLogger", e);
            }
        };
        logThreadPoolBeanConfig.sysLogThreadPool().execute(runnable);
    }

    public String getSaveName(String corpid, Integer businessType, PaasFormEntityExt paasFormEntityExt, PaasFormDataEntity paasFormDataEntityExt ) throws XbbException {
        return null;
    }



    /**
     * 修改成员添加标签时候产生的日志
     *
     *
     * @param loginUser 当前登录人
     * @param formId 表单id
     * @param userId 当前被操作对象的用户id
     * @param corpid 公司id
     * @param businessType  业务类型
     * @param object 不同业务的主数据实体
     * @param isMain 1：负责人 0：协同人
     * @param httpHeader 请求头
     * @param lbIdFormList 老的表单标签
     * @param lbIdSysList 老的系统标签
     * @param dbLbIdFormList 数据库的表单标签
     * @param dbLbIdSysList 数据库的系统标签
     */
    public void saveUpdateLabelLogger(UserVO loginUser,  Long formId, String userId, String corpid, Integer businessType, Object object, Integer isMain,
                                      String httpHeader, List<Long> lbIdFormList, List<Long> lbIdSysList, List<Long> dbLbIdFormList, List<Long> dbLbIdSysList, Long beforeUpdateTime) {
        Runnable runnable = () -> {
            OperateModuleTypeEnum operateModuleTypeEnum = OperateModuleTypeEnum.RESPONSIBLE_TEAM;
            OperateTypeEnum operateTypeEnum = OperateTypeEnum.EDIT;
            UserEntity userEntity = userModel.getByKey(userId, corpid);
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(object, paasFormDataEntity);
            PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
            String message = I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_EDIT_LABEL);
            String loginUserId = loginUser.getUserId();
            String userName = loginUser.getName();
            String formName = paasFormEntityExt.getName();
            String content = "";
            if (Objects.equals(isMain, BasicConstant.ONE)) {
                content = I18nMessageUtil.getMessage(ListBatchConstant.MAIN_USER_ALIAS);
            }else {
                content = I18nMessageUtil.getMessage(ListBatchConstant.CO_USER_ALIAS);
            }
            try {
                String operateObject = userEntity.getName();
                String objectName = getSaveName(corpid, businessType, paasFormEntityExt, paasFormDataEntity);
                String memo = String.format(message, userName, formName, objectName, content, operateObject);
                List<SysLabelEntity> sysLabelEntities = sysLabelModel.getByLabelIdIn(corpid, lbIdSysList);
                List<FormLabelEntity> formLabelEntities = formLabelModel.getByLabelIdIn(corpid, lbIdFormList);
                StringBuilder sbAfter = new StringBuilder();
                String paramSysLabelInfoStr = sysLabelEntities.stream().map(sysLabelEntity -> sysLabelEntity.getName()).collect(Collectors.joining(","));
                sbAfter.append(paramSysLabelInfoStr);
                String paramFormLabelInfoStr = formLabelEntities.stream().map(formLabelEntity -> formLabelEntity.getName()).collect(Collectors.joining(","));
                sbAfter.append(paramFormLabelInfoStr);
                List<SysLabelEntity> dbSysLabelEntities = sysLabelModel.getByLabelIdIn(corpid, dbLbIdSysList);
                List<FormLabelEntity> dbFormLabelEntities = formLabelModel.getByLabelIdIn(corpid, dbLbIdFormList);
                StringBuilder sbBefore = new StringBuilder();
                String dbSysLabelInfoStr = dbSysLabelEntities.stream().map(sysLabelEntity -> sysLabelEntity.getName()).collect(Collectors.joining(","));
                String dbFormLabelInfoStr = dbFormLabelEntities.stream().map(formLabelEntity -> formLabelEntity.getName()).collect(Collectors.joining(","));
                sbBefore.append(dbSysLabelInfoStr).append(dbFormLabelInfoStr);
                List<DetailLogPojo> detailArr = new ArrayList<>();
                DetailLogPojo detailLogPojo = new DetailLogPojo(I18nMessageUtil.getMessage(TeamMembersConstant.LABELS),
                        sbBefore.toString(), sbAfter.toString());
                detailArr.add(detailLogPojo);
                userTeamHelp.getStringTime(beforeUpdateTime, DateUtil.getNow(), detailArr);
                mongoLogHelp.buildLog4DetailArr(detailArr, corpid, userId, userName, operateModuleTypeEnum, operateTypeEnum,
                        paasFormDataEntity.getId().toString(), operateObject, memo, httpHeader);
            } catch (XbbException e){
                LOG.error("com.xbongbong.paas.service.team.strategy.AbstractTeamStrategy.saveUpdateLabelLogger", e);
            }
        };
        logThreadPoolBeanConfig.sysLogThreadPool().execute(runnable);
    }

    /**
     * 获取业务列表中与团队有关的一些批量操作的权限
     *
     * @param formDataListDTO
     * @param explains
     * @return
     */
    @Override
    public TeamListBatchPermissionVO getTeamListBatchPermission(FormDataListDTO formDataListDTO, List<FieldAttrEntity> explains) throws XbbException {
        TeamListBatchPermissionVO teamListBatchPermissionVO = new TeamListBatchPermissionVO();
        //表单共享标识，true：共享  false：隔离
        boolean formShareTag = true;
        Integer saasMark = formDataListDTO.getSaasMark();
        Integer businessType = formDataListDTO.getBusinessType();
        //首先进行当前表单模式判断,PAAS肯定是按照共享模式的按钮走的。
        if (Objects.equals(SaasMarkEnum.PAAS.getCode(), saasMark)) {
            formShareTag = true;
        }else {
            String corpid = formDataListDTO.getCorpid();
            Long formId = formDataListDTO.getFormId();
            formShareTag = userTeamHelp.getFormShareTag(corpid, formId, businessType);
        }
        //判断真正隔离
        boolean trueIsolation = !formShareTag && (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode()));
        if (trueIsolation) {
            //隔离模式
            teamListBatchPermissionVO = teamIsolationListBatchPermission(formDataListDTO, explains);
        }else {
            //共享模式
            teamListBatchPermissionVO = teamShareListBatchPermission(formDataListDTO, explains);
        }
        if (trueIsolation) {
            teamListBatchPermissionVO.setModel(FormPatternEnum.FORM_ISOLATION.getModel());
        }else {
            teamListBatchPermissionVO.setModel(FormPatternEnum.FORM_SHARE.getModel());
        }
        return teamListBatchPermissionVO;
    }


    /**
     * 共享模式下列表中关于团队批量操作按钮的权限封装
     * (1)批量添加负责人：首先多负责人表单，并且负责人字段要存在且启用
     * (2)批量删除负责人：首先多负责人表单，并且负责人字段要存在且启用
     * (3)批量添加协同人：首先需要有协同人字段并且启用
     * (4)批量删除协同人：首先需要有协同人字段并且启用
     * (5)批量移交负责人；首先需要有负责人字段并且启用
     *
     *
     * @param formDataListDTO
     * @param explains
     * @return
     */
    private TeamListBatchPermissionVO teamShareListBatchPermission(FormDataListDTO formDataListDTO, List<FieldAttrEntity> explains) throws XbbException {
        TeamListBatchPermissionVO teamListBatchPermissionVO = new TeamListBatchPermissionVO();
        Integer businessType = formDataListDTO.getBusinessType();
        boolean batchAddMain = true;
        boolean batchDelMain = true;
        boolean batchAddCo = true;
        boolean batchIsolationAddCo = false;
        boolean batchDelCo = true;
        boolean batchIsolationDelCo = false;
        boolean batchHandleOverMain = true;
        boolean batchIsolationHandleOverMain = false;
        boolean batchAddTeam = false;
        boolean batchDisbandTeam = false;
        boolean batchDistributor = true;
        Map<String, Boolean> teamMap = new HashMap<>();
        //这边仓库有个移交按钮功能
        if (Objects.equals(XbbRefTypeEnum.WAREHOUSE.getCode(), businessType)) {
            teamMap.put(SaasBatchEnum.HANDOVER.getAttr(), true);
            teamListBatchPermissionVO.setTeamMap(teamMap);
            return teamListBatchPermissionVO;
        }

        FieldAttrEntity ownerFieldAttrEntity = new FieldAttrEntity();
        FieldAttrEntity coFieldAttrEntity = new FieldAttrEntity();
        for (FieldAttrEntity fieldAttrEntity : explains) {
            if (Objects.equals(fieldAttrEntity.getAttr(), FieldTypeEnum.OWNERID.getAlias())) {
                ownerFieldAttrEntity = fieldAttrEntity;
            }else if (Objects.equals(fieldAttrEntity.getAttr(), FieldTypeEnum.COUSERID.getAlias())) {
                coFieldAttrEntity = fieldAttrEntity;
            }
        }
        //判断是不是多负责人表单
        //判断是不是多负责人表单
        List<Integer> allBusinessList = FormOwnerUniqueEnum.getAllBusinessList();
        Integer feeType = commonHelp.getCurrentCompanyPackage(formDataListDTO.getCorpid());
        boolean teamOwnerUniqueTag = !Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType()) && allBusinessList.contains(formDataListDTO.getBusinessType());
        Integer multipleValue = ownerFieldAttrEntity.getMultiple();
        if (Objects.isNull(multipleValue) || teamOwnerUniqueTag) {
            FormOwnerUniqueEnum formOwnerUniqueEnum = FormOwnerUniqueEnum.getFormOwnerUniqueByBus(businessType);
            multipleValue = formOwnerUniqueEnum.getValue();
        }
        //判断批量新增负责人权限
        boolean publicTag = Objects.equals(XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode(), formDataListDTO.getSubBusinessType()) ||
                Objects.equals(XbbRefTypeEnum.CLUE_PUBLIC.getCode(), formDataListDTO.getSubBusinessType());
        if (Objects.isNull(ownerFieldAttrEntity) || Objects.equals(ownerFieldAttrEntity.getIsOpen(), BasicConstant.ZERO)
                || (!Objects.equals(multipleValue, BasicConstant.ONE) && !publicTag)) {
            batchAddMain = false;
            batchDelMain = false;
            batchDistributor= false;
        }
        //判断批量新增协同人权限
        if (Objects.isNull(coFieldAttrEntity) || Objects.equals(coFieldAttrEntity.getIsOpen(), BasicConstant.ZERO)) {
            batchAddCo = false;
            batchDelCo = false;
        }
        //判断批量移交负责人权限
        if (Objects.isNull(ownerFieldAttrEntity) || Objects.equals(ownerFieldAttrEntity.getIsOpen(), BasicConstant.ZERO)) {
            batchHandleOverMain = false;
        }
        teamMap.put(SaasBatchEnum.ADD_MAIN_USER.getAttr(), batchAddMain);
        teamMap.put(SaasBatchEnum.DISTRIBUTION.getAttr(), batchDistributor);
        teamMap.put(SaasBatchEnum.DEL_MAIN_USER.getAttr(), batchDelMain);
        teamMap.put(SaasBatchEnum.ADD_TEAM_PERSON.getAttr(), batchAddCo);
        teamMap.put(SaasBatchEnum.ADD_ISOLATION_TEAM_PERSON.getAttr(), batchIsolationAddCo);
        teamMap.put(SaasBatchEnum.DEL_TEAM_PERSON.getAttr(), batchDelCo);
        teamMap.put(SaasBatchEnum.DEL_ISOLATION_TEAM_PERSON.getAttr(), batchIsolationDelCo);
        teamMap.put(SaasBatchEnum.HANDOVER.getAttr(), batchHandleOverMain);
        teamMap.put(SaasBatchEnum.HANDOVER_CHANGE_MAIN.getAttr(), batchIsolationHandleOverMain);
        teamMap.put(SaasBatchEnum.ADD_TEAM.getAttr(), batchAddTeam);
        teamMap.put(SaasBatchEnum.DISBAND_TEAM.getAttr(), batchDisbandTeam);
        teamListBatchPermissionVO.setTeamMap(teamMap);
        return teamListBatchPermissionVO;
    }


    /**
     * 隔离模式下列表中关于团队批量操作按钮的权限封装
     * （1）批量添加协同人：
     *      1.管理员、老板角色、开启数据权限为全公司的人员
     *      2.协同人字段存在且开启
     * （2）批量删除协同人:
     *      1.管理员、老板角色、开启数据权限为全公司的人员
     *      2.协同人字段存在且开启
     * （3）批量创建团队
     *      1.管理员、老板角色、开启数据权限为全公司的人员
     *      2.负责人字段存在且开启
     * （4）批量解散团队
     *      1. 管理员、老板角色、开启数据权限为全公司的人员
     *      2. 负责人字段存在且开启
     * （5）批量移交负责人
     *      1. 管理员、老板角色、开启数据权限为全公司的人员
     *      2. 负责人字段存在且开启
     * @param formDataListDTO
     * @param explains
     * @return
     */
    private TeamListBatchPermissionVO teamIsolationListBatchPermission(FormDataListDTO formDataListDTO, List<FieldAttrEntity> explains) throws XbbException {
        TeamListBatchPermissionVO teamListBatchPermissionVO = new TeamListBatchPermissionVO();
        boolean batchAddMain = false;
        boolean batchDelMain = false;
        boolean batchAddCo = false;
        boolean batchIsolationAddCo = true;
        boolean batchDelCo = false;
        boolean batchIsolationDelCo = true;
        boolean batchHandleOverMain = false;
        boolean batchIsolationHandleOverMain = true;
        boolean batchAddTeam = true;
        boolean batchDisbandTeam = true;
        boolean batchDistributor = false;
        UserVO loginUser = formDataListDTO.getLoginUser();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(loginUser, userEntity);
        Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.SAAS, formDataListDTO.getBusinessType(), 0L);
        boolean adminOrBossTag = loginUser.isAdminOrBoss() || Objects.equals(5, dataPermission);
        FieldAttrEntity ownerFieldAttrEntity = new FieldAttrEntity();
        FieldAttrEntity coFieldAttrEntity = new FieldAttrEntity();
        for (FieldAttrEntity fieldAttrEntity : explains) {
            if (Objects.equals(fieldAttrEntity.getAttr(), FieldTypeEnum.OWNERID.getAlias())) {
                ownerFieldAttrEntity = fieldAttrEntity;
            }else if (Objects.equals(fieldAttrEntity.getAttr(), FieldTypeEnum.COUSERID.getAlias())) {
                coFieldAttrEntity = fieldAttrEntity;
            }
        }
        //判断是不是多负责人表单
        List<Integer> allBusinessList = FormOwnerUniqueEnum.getAllBusinessList();
        Integer feeType = commonHelp.getCurrentCompanyPackage(formDataListDTO.getCorpid());
        boolean teamOwnerUniqueTag = !Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType()) && allBusinessList.contains(formDataListDTO.getBusinessType());
        Integer multipleValue = ownerFieldAttrEntity.getMultiple();
        if (Objects.isNull(multipleValue) || teamOwnerUniqueTag) {
            FormOwnerUniqueEnum formOwnerUniqueEnum = FormOwnerUniqueEnum.getFormOwnerUniqueByBus(formDataListDTO.getBusinessType());
            multipleValue = formOwnerUniqueEnum.getValue();
        }
        boolean ownerTag = Objects.equals(ownerFieldAttrEntity.getIsOpen(), BasicConstant.ZERO);
        boolean coUserTag = Objects.equals(coFieldAttrEntity.getIsOpen(), BasicConstant.ZERO);
        boolean publicTag = Objects.equals(XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode(), formDataListDTO.getSubBusinessType())
                || Objects.equals(XbbRefTypeEnum.CLUE_PUBLIC.getCode(), formDataListDTO.getSubBusinessType());
        if (publicTag) {
            batchDistributor = true;
        }
        if (!adminOrBossTag || ownerTag || !Objects.equals(multipleValue, BasicConstant.ONE)) {
            batchAddTeam = false;
            batchDisbandTeam = false;
        }

        if (!adminOrBossTag) {
            if (!(loginUser.getPermSet().contains(ProPermissionAliasEnum.CUSTOMER_HANDOVER.getAlias()))) {
                batchIsolationHandleOverMain = false;
            }
        } else if (ownerTag) {
            batchIsolationHandleOverMain = false;
        }

        if (!adminOrBossTag || coUserTag) {
            batchAddCo = false;
            batchDelCo = false;
        }
        Map<String, Boolean> teamMap = new HashMap<>();
        teamMap.put(SaasBatchEnum.ADD_MAIN_USER.getAttr(), batchAddMain);
        teamMap.put(SaasBatchEnum.DISTRIBUTION.getAttr(), batchDistributor);
        teamMap.put(SaasBatchEnum.DEL_MAIN_USER.getAttr(), batchDelMain);
        teamMap.put(SaasBatchEnum.ADD_TEAM_PERSON.getAttr(), batchAddCo);
        teamMap.put(SaasBatchEnum.ADD_ISOLATION_TEAM_PERSON.getAttr(), batchIsolationAddCo);
        teamMap.put(SaasBatchEnum.DEL_TEAM_PERSON.getAttr(), batchDelCo);
        teamMap.put(SaasBatchEnum.DEL_ISOLATION_TEAM_PERSON.getAttr(), batchIsolationDelCo);
        teamMap.put(SaasBatchEnum.HANDOVER.getAttr(), batchHandleOverMain);
        teamMap.put(SaasBatchEnum.HANDOVER_CHANGE_MAIN.getAttr(), batchIsolationHandleOverMain);
        teamMap.put(SaasBatchEnum.ADD_TEAM.getAttr(), batchAddTeam);
        teamMap.put(SaasBatchEnum.DISBAND_TEAM.getAttr(), batchDisbandTeam);
        teamListBatchPermissionVO.setTeamMap(teamMap);
        return teamListBatchPermissionVO;
    }

    /**
     * 团队新增权限
     * 1. 管理员、老板角色以及开启数据权限为全公司的人员
     * 2. 同时具有负责人新增以及协同人新增的字段权限
     *
     * @param teamDetailDTO
     * @param teamDetailIsolationVO
     * @param isolationOwnerSet
     * @param allCouserSet
     * @param ultimateTag           是否为旗舰版
     * @param teamRelatedPojo
     * @param paasFormDataEntityExt
     */
    private void packageIsolationAddTeam(TeamDetailDTO teamDetailDTO, TeamDetailIsolationVO teamDetailIsolationVO, Set<String> isolationOwnerSet, Set<String> allCouserSet, Boolean mainDataCheck, Boolean ultimateTag,
                                         TeamRelatedPojo teamRelatedPojo, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        if (Objects.equals(false, teamRelatedPojo.getBasicFormEdit())) {
            teamDetailIsolationVO.setAddTeam(false);
        } else if (mainDataCheck) {
            Integer businessType = teamDetailDTO.getBusinessType();
            UserVO loginUser = teamDetailDTO.getLoginUser();
            Map<String, FieldAttrEntity> explainMap = getExplainMap(teamDetailDTO);
            FieldAttrEntity ownerFieldAttr =  explainMap.get(FieldTypeEnum.OWNERID.getAlias());
            HandlerExplainDTO handlerExplainDTO = getSearchUserFieldPerCondtion(teamDetailDTO, paasFormDataEntityExt);
            handlerExplainDTO.setOwnerId(new ArrayList<>(isolationOwnerSet));
            handlerExplainDTO.setCoUserId(new ArrayList<>(allCouserSet));
            //负责人新增权限
            Boolean mainAddPermission = ExplainUtil.advancedOperationHavePermission(ownerFieldAttr, handlerExplainDTO, FieldAdvanceOperationEnum.ADD.getOperation());
            if (!mainAddPermission) {
                teamDetailIsolationVO.setAddTeam(false);
                return;
            }
            //如果负责人唯一，并且已经有一个团队了，则不允许新增团队
            Integer multiple = ownerFieldAttr.getMultiple();
            if ( (!ultimateTag && FormOwnerUniqueEnum.getDefaultBusinessList().contains(businessType)) || Objects.isNull(multiple)) {
                //非旗舰版或为空，负责人唯一属性用默认值
                FormOwnerUniqueEnum formOwnerUniqueEnum = FormOwnerUniqueEnum.getFormOwnerUniqueByBus(businessType);
                multiple = formOwnerUniqueEnum.getValue();
            }
            if (Objects.equals(OwnerUniqueDefaultEnum.UNIQUE.getValue(), multiple) &&
                    (CollectionsUtil.isNotEmpty(teamDetailIsolationVO.getTeamGroups()) && teamDetailIsolationVO.getTeamGroups().size() >= BasicConstant.ONE)) {
                teamDetailIsolationVO.setAddTeam(false);
                return;
            }
            //管理员、老板角色、以及数据权限全公司的人员
            UserEntity userEntity = new UserEntity();
            BeanUtil.copyProperties(loginUser, userEntity);
            Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.SAAS, teamDetailDTO.getBusinessType(), 0L);
            Boolean hasMaxPermission = loginUser.isAdminOrBoss() || Objects.equals(dataPermission, 5);
            if (hasMaxPermission) {
                teamDetailIsolationVO.setAddTeam(true);
                return;
            }
        }else {
            teamDetailIsolationVO.setAddTeam(false);
        }

    }

    /**
     * 封装历史协同人的相关信息
     * 权限：（1）标签编辑：有表单编辑权限人员
     * （2）删除协同人：管理员、老板角色、负责人、有编辑权限的协同人；同时有协同人字段删除权限人员
     *
     * @param teamDetailDTO         团队详情tab传参
     * @param historyCoInfoPojo     独立协同人实体信息
     * @param teamDetailIsolationVO 隔离模式下返回的信息
     * @param userEntityMap
     * @param paasFormDataEntityExt
     */
    private void packageIsolationHistoryCoPer(TeamDetailDTO teamDetailDTO, HistoryCoInfoPojo historyCoInfoPojo, TeamDetailIsolationVO teamDetailIsolationVO,
                                              Map<String, UserTeamEntity> userEntityMap, FieldAttrEntity coUserFieldAttr, Boolean mainDataCheck,
                                              Set<String> isolationOwnerSet, Set<String> allCouserSet, TeamRelatedPojo teamRelatedPojo, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        IndependentCoPermissionPojo permissions = new IndependentCoPermissionPojo(false, true, true);
        if (Objects.equals(false, teamRelatedPojo.getBasicFormEdit())) {
            permissions = new IndependentCoPermissionPojo(false, false, false);
        } else if (mainDataCheck) {
            //判断是不是超管、最大数据权限以及负责人以及具有编辑权限的协同人
            String userId = teamDetailDTO.getUserId();
            UserVO loginUser = teamDetailDTO.getLoginUser();
            Integer businessType = teamDetailDTO.getBusinessType();
            UserTeamEntity userTeamEntity = Objects.isNull(userEntityMap.get(userId)) ? new UserTeamEntity() : userEntityMap.get(userId);
            Integer isMain = userTeamEntity.getIsMain();
            UserEntity userEntity = new UserEntity();
            BeanUtil.copyProperties(loginUser, userEntity);
            Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.SAAS, teamDetailDTO.getBusinessType(), 0L);
            Boolean hasMaxPermission = loginUser.isAdminOrBoss() || Objects.equals(5, dataPermission);
            Boolean teamMain = hasMaxPermission || Objects.equals(BasicConstant.ONE, isMain);
            //是否是具有编辑权限的协同人
            Integer userFormPer = userTeamEntity.getFormPermission();
            if (Objects.isNull(userFormPer)) {
                FormCoUserDefaultPermissionEnum formCoUserDefaultPermissionEnum = FormCoUserDefaultPermissionEnum.getFormPatternEnumByBus(businessType);
                userFormPer = formCoUserDefaultPermissionEnum.getDefaultPermissionValue();
            }
            Boolean teamCoEdit = Objects.equals(BasicConstant.ZERO, isMain) && Objects.equals(CoUserPermissionEnum.EDIT.getPermissionValue(), userFormPer);
            if (!teamMain && !teamCoEdit) {
                permissions.setEditCoFormPermission(false);
            }
        /*//判断表单解释的协同人可编辑权限
        Integer feeType = commonHelp.getCurrentCompanyPackage(teamDetailDTO.getCorpid());
        Integer formPermission = coUserFieldAttr.getFormPermission();
        //如果套餐是旗舰版就按照表单设置那边走，如果套餐是非旗舰版的就按照默认规则走
        if (!Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType())) {
            FormCoUserDefaultPermissionEnum formCoUserDefaultPermissionEnum = FormCoUserDefaultPermissionEnum.getFormPatternEnumByBus(businessType);
            formPermission = formCoUserDefaultPermissionEnum.getDefaultPermissionValue();
        } else {
            if (Objects.isNull(formPermission)) {
                FormCoUserDefaultPermissionEnum formCoUserDefaultPermissionEnum = FormCoUserDefaultPermissionEnum.getFormPatternEnumByBus(businessType);
                formPermission = formCoUserDefaultPermissionEnum.getDefaultPermissionValue();
            }
        }
        if (Objects.equals(CoUserPermissionEnum.READ.getPermissionValue(), formPermission)) {
            permissions.setEditCoFormPermission(false);
        }else {

        }*/
            //编辑标签权限
            if (!teamMain && !teamCoEdit) {
                permissions.setEditLabel(false);
            }
            //独立协同人删除按钮
            HandlerExplainDTO handlerExplainDTO = getSearchUserFieldPerCondtion(teamDetailDTO, paasFormDataEntityExt) ;
            handlerExplainDTO.setOwnerId(new ArrayList<>(isolationOwnerSet));
            handlerExplainDTO.setCoUserId(new ArrayList<>(allCouserSet));
            Boolean haveCoUserDelPermission = ExplainUtil.advancedOperationHavePermission(coUserFieldAttr, handlerExplainDTO, FieldAdvanceOperationEnum.DEL.getOperation());
            if (haveCoUserDelPermission && (teamMain || teamCoEdit)) {
                permissions.setCoDel(true);
            }
        }else {
            permissions = new IndependentCoPermissionPojo(false, false, false);
        }
        historyCoInfoPojo.setPermissions(permissions);
        teamDetailIsolationVO.setHistoryCoInfo(historyCoInfoPojo);
    }

    /**
     * 得到共享模式下协同人编辑权限
     * 超管、老板角色、开启全公司的数据权限；团队内负责人、团队内有编辑权的协同人；其他的就是主管下面的负责人在这团队中也能编辑
     *
     *
     * @param teamDetailDTO 团队详情入参
     * @param userTeamEntity 所有协同人信息
     * @param teamRelatedPojo 中间流转参数实体
     * @return
     */
    private boolean getShareCoEditPer(TeamDetailDTO teamDetailDTO, UserTeamEntity userTeamEntity,
                                      TeamRelatedPojo teamRelatedPojo, Set<String> teamUserIdList) throws XbbException {
        Integer businessType = teamDetailDTO.getBusinessType();
        if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType) ||
                Objects.equals(XbbRefTypeEnum.WAREHOUSE.getCode(), businessType)) {
            return false;
        }
        Integer saasMark = teamDetailDTO.getSaasMark();
        UserVO loginUser = teamDetailDTO.getLoginUser();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(loginUser, userEntity);
        Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.getByCode(saasMark), teamDetailDTO.getBusinessType(), teamDetailDTO.getMenuId());
        Boolean isAdminOrBoss = loginUser.isAdminOrBoss();
        Boolean hasMaxPermission = Objects.equals(DataPermissionEnum.ALL.getCode(), dataPermission);
        if (isAdminOrBoss || hasMaxPermission) {
            return true;
        }
        if (hasMaxPermission) {
            return teamRelatedPojo.getBasicFormEdit();
        }
        if (Objects.isNull(userTeamEntity)) {
            //代表是有这条数据的数据权限，但是不在团队中；
            //要么是共享权限可看的，要么是有团队中某人的数据权限
            List<String> userIdIn = userModel.getSubIdListByDataPermission(dataPermission, loginUser.getUserId(), loginUser.getCorpid(), BasicConstant.ZERO,false);
            if(CollectionUtils.intersection(userIdIn, teamUserIdList).size() > Constant.ZERO){
                //有团队中成员的数据权限，则直接判断是否有该表单的编辑权，若有就能编辑
                return teamRelatedPojo.getBasicFormEdit();
            }else{
                //共享权限可见的,直接给false  后续会有校验
                return false;
            }

        }else {
            Integer isMain = userTeamEntity.getIsMain();
            if (Objects.equals(BasicConstant.ONE, isMain)) {
                //负责人都是可编辑的
                return teamRelatedPojo.getBasicFormEdit();
            }else if (Objects.equals(BasicConstant.ZERO, isMain)) {
                //如果是协同人就需要判断当前协同人是不是有编辑权限
                Integer formPermission = userTeamEntity.getFormPermission();
                if (Objects.isNull(formPermission)) {
                    formPermission = FormCoUserDefaultPermissionEnum.getDefaultPerByBus(businessType);
                }
                if (Objects.equals(formPermission, CoUserPermissionEnum.READ.getPermissionValue())) {
                    return false;
                }else {
                    return teamRelatedPojo.getBasicFormEdit();
                }
            }
        }
        return true;
    }

    /**
     * 由子类实现
     * @param dataId
     * @param userIdIn
     * @param corpid
     * @param indexTypeEnum
     * @return
     */
    protected BoolQueryBuilder permissionQueryIsMain(Long dataId, List<String> userIdIn, String corpid, IndexTypeEnum indexTypeEnum) {
        BoolQueryBuilder boolQueryBuilder = permissionQuery(dataId, userIdIn, corpid, indexTypeEnum);

        return boolQueryBuilder;
    }

    /**
     * 由子类实现
     * @param dataId
     * @param userIdIn
     * @param corpid
     * @param indexTypeEnum
     * @return
     */
    protected BoolQueryBuilder permissionQuery(Long dataId, List<String> userIdIn, String corpid, IndexTypeEnum indexTypeEnum) {
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        return boolQueryBuilder;
    }

    /**
     * 由子类实现
     * 有团队的详情权限校验
     * @param businessType
     * @return
     */
    protected Boolean checkPermissionByTeam(Integer saasMark, Integer businessType, BoolQueryBuilder boolQueryBuilder) throws XbbException {
        return false;
    }
    /**
     * 获取基础的移交权限
     *
     * @param teamDetailDTO 团队详情入参
     * @return
     */
    private boolean getBasicHandleOver(TeamDetailDTO teamDetailDTO) throws XbbException {
        String corpid = teamDetailDTO.getCorpid();
        Long appId = teamDetailDTO.getAppId();
        Long menuId = teamDetailDTO.getMenuId();
        Integer saasMark = teamDetailDTO.getSaasMark();
        Integer businessType = teamDetailDTO.getBusinessType();
        UserVO loginUser = teamDetailDTO.getLoginUser();
        String userId = loginUser.getUserId();
        if (Objects.equals(SaasMarkEnum.PAAS.getCode(), saasMark)) {
            UserFormPermissionVO userFormPermissionInternal =  userModel.getUserFormPermission(corpid, userId, appId, menuId);
            PermissionTermsPojo permission = userFormPermissionInternal.getFormPermission().getPermission();
            Boolean isAdminOrBoss = userFormPermissionInternal.getIsAdminOrBoss();
            if (Objects.equals(BasicConstant.ZERO, permission.getHandleOver()) && !isAdminOrBoss ) {
                return false;
            }
        }else {
            //下面是saas表单的移交权限判断
            HandoverPermissionAliasEnum handoverPermissionAlias = HandoverPermissionAliasEnum.getByCode(businessType);
            if (Objects.equals(teamDetailDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode()) && !teamDetailDTO.getLoginUser().getPermSet().contains(handoverPermissionAlias.getAlias())) {
                return false;
            }
        }
        return true;
    }


    /**
     * 解散团队权限封装
     *  1. 管理员、老板角色以及开启数据权限为全公司的人员或团队内负责人
     *
     * @param isolationUserPermissionPojo 权限实体
     * @param teamRelatedPojo 中间流转参数实体
     */
    private void packageIsolationDisband(TeamDetailDTO teamDetailDTO, IsolationUserPermissionPojo isolationUserPermissionPojo, TeamRelatedPojo teamRelatedPojo,
                                         HandlerExplainDTO handlerExplainDTO, FieldAttrEntity ownerFieldAttr, FieldAttrEntity coUserFieldAttr, Set<String> isolationOwnerSet) throws XbbException {
        //解散团队首先需要当前登录人同时具备删除负责人、删除协同人的权限
        Boolean haveOwnerUserDelPermission = ExplainUtil.advancedOperationHavePermission(ownerFieldAttr, handlerExplainDTO, FieldAdvanceOperationEnum.DEL.getOperation());
        Boolean haveCoUserDelPermission = ExplainUtil.advancedOperationHavePermission(coUserFieldAttr, handlerExplainDTO, FieldAdvanceOperationEnum.DEL.getOperation());
        Integer multiple = ownerFieldAttr.getMultiple();
        if (Objects.isNull(multiple)) {
            multiple = FormOwnerUniqueEnum.getFormOwnerUniqueByBus(teamDetailDTO.getBusinessType()).getValue();
        }
        if (Objects.equals(OwnerUniqueDefaultEnum.UNIQUE.getValue(), multiple) && isolationOwnerSet.size() == BasicConstant.ONE) {
            //负责人唯一并且只有一个团队的也没有解散团队按钮
            isolationUserPermissionPojo.setDisbandTeam(false);
            return;
        }
        if (Objects.equals(false, haveOwnerUserDelPermission) || Objects.equals(false, haveCoUserDelPermission)) {
            isolationUserPermissionPojo.setDisbandTeam(false);
            return;
        }
        boolean disbandTeam = teamRelatedPojo.getBasicTeamMain();
        isolationUserPermissionPojo.setDisbandTeam(disbandTeam);
    }


    /**
     * 隔离模式下相关权限封装：业务目前也是只有客户、线索
     * (1)添加团队协同人：
     * i. 管理员、老板角色、开启数据权限为全公司的人员、团队内负责人、团队内有编辑权限的协同人
     * (2)移交团队
     * 1. 管理员、老板角色以及开启数据权限为全公司的人员
     * 2、同时具有负责人新增、删除字段权限
     *
     * @param teamDetailDTO         入参参数
     * @param teamGroupPojo         封装的团队实体
     * @param teamRelatedPojo       中间流转参数实体
     * @param userEntityMap
     * @param paasFormDataEntityExt
     * @return 需要对这个封装的团队实体按照权限再分一层
     */
    private IsolationUserPermissionPojo packageIsolationUserPermission(TeamDetailDTO teamDetailDTO, TeamGroupPojo teamGroupPojo,
                                                                       TeamRelatedPojo teamRelatedPojo, Map<String, UserTeamEntity> userEntityMap,
                                                                       FieldAttrEntity ownerFieldAttr, FieldAttrEntity coUserFieldAttr,
                                                                       Set<String> currentTeamCoopUserSet, String ownerId, Set<String> isolationOwnerSet,
                                                                       Boolean mainDataCheck, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        HandlerExplainDTO handlerExplainDTO = getSearchUserFieldPerCondtion(teamDetailDTO, paasFormDataEntityExt) ;
        handlerExplainDTO.setOwnerId(new ArrayList<>(Arrays.asList(ownerId)));
        handlerExplainDTO.setCoUserId(new ArrayList<>(currentTeamCoopUserSet));
        IsolationUserPermissionPojo isolationUserPermissionPojo = new IsolationUserPermissionPojo(true, true, true, true,
                true, true, true);
        if (!mainDataCheck || Objects.equals(false, teamRelatedPojo.getBasicFormEdit())) {
            isolationUserPermissionPojo = new IsolationUserPermissionPojo(false, false, false, false,
                    false, false, false);
            return isolationUserPermissionPojo;
        }
        UserVO loginUser = teamDetailDTO.getLoginUser();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(loginUser, userEntity);
        Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.SAAS, teamDetailDTO.getBusinessType(), 0L);
        Boolean hasMaxPermission = loginUser.isAdminOrBoss() || Objects.equals(DataPermissionEnum.ALL.getCode(), dataPermission);
        //一些权限进行前置处理
        boolean formEdit = getIsolationCoEditPer(teamDetailDTO, teamRelatedPojo, userEntityMap, currentTeamCoopUserSet, dataPermission, hasMaxPermission);
        teamRelatedPojo.setFormEdit(formEdit);
        boolean basicTeamMain = getUserCurrentTeamMainPerSen(teamDetailDTO, teamGroupPojo.getMainUserArr(), hasMaxPermission);
        boolean userCurrentTeamMain = getUserCurrentTeamMainPer(teamDetailDTO, teamGroupPojo.getMainUserArr(), teamRelatedPojo, hasMaxPermission);
        teamRelatedPojo.setBasicTeamMain(basicTeamMain);
        teamRelatedPojo.setUserCurrentTeamMain(userCurrentTeamMain);
        //隔离模式下协同人相关权限
        packageIsonlationCoPermission(coUserFieldAttr, handlerExplainDTO, isolationUserPermissionPojo, teamRelatedPojo);
        //标签编辑权限
        packageIsolationEditLabel(isolationUserPermissionPojo, teamRelatedPojo, teamDetailDTO.getCorpid());
        //编辑团队协同人权限
        packageIsolationEditCoFormPer(teamDetailDTO, isolationUserPermissionPojo, teamRelatedPojo);
        //隔离模式下移交(隔离模式的移交，不涉及共享权限的判断)
        packageIsolationChangeMain(isolationUserPermissionPojo, handlerExplainDTO, ownerFieldAttr, teamRelatedPojo, teamGroupPojo);
        //解散团队权限
        packageIsolationDisband(teamDetailDTO, isolationUserPermissionPojo, teamRelatedPojo, handlerExplainDTO, ownerFieldAttr, coUserFieldAttr, isolationOwnerSet);
        //编辑团队名称权限
        packageIsolationEditTeam(isolationUserPermissionPojo, teamRelatedPojo);
        return isolationUserPermissionPojo;
    }


    /**
     * 得到隔离模式下协同人编辑权限
     *
     * @param teamDetailDTO 团队详情入参
     * @param teamRelatedPojo 中间流转参数实体
     * @return
     */
    private boolean getIsolationCoEditPer(TeamDetailDTO teamDetailDTO, TeamRelatedPojo teamRelatedPojo, Map<String,
            UserTeamEntity> userEntityMap, Set<String> currentTeamCoopUserSet, Integer dataPermission, Boolean hasMaxPermission) throws XbbException {
        UserVO loginUser = teamDetailDTO.getLoginUser();
        String userId = loginUser.getUserId();
        UserTeamEntity userTeamEntity = Objects.isNull(userEntityMap.get(userId)) ? new UserTeamEntity() : userEntityMap.get(userId);
        Integer businessType = teamDetailDTO.getBusinessType();
        //基础的表单权限判断
        boolean basicFormEdit = teamRelatedPojo.getBasicFormEdit();
        if (!basicFormEdit) {
            return false;
        }
        if (Objects.equals(BasicConstant.ZERO, userTeamEntity.getIsMain())) {
            //隔离模式下如果是协同人，则首先需要满足当前登录人在这个团队里面
            if (!currentTeamCoopUserSet.contains(userId)) {
                return false;
            }
            Integer formPermission = userTeamEntity.getFormPermission();
            if (Objects.isNull(formPermission)) {
                formPermission = FormCoUserDefaultPermissionEnum.getDefaultPerByBus(businessType);
            }
            if (Objects.equals(userId, userTeamEntity.getUserId()) &&
                    Objects.equals(CoUserPermissionEnum.READ.getPermissionValue(), formPermission)) {
                return false;
            }
        }else {
            //非协同人
            //1.超管boss或者全数据范围的人、2.负责人、3.拥有团队里的人的数据权限、4.共享权限下的授权人员（这种不允许编辑，隔离模式不受共享规则影响）
            //如果不是前三种，则不能给编辑权。

            //判断是否为负责人
            boolean isMainUser;
            if(Objects.isNull(userEntityMap.get(userId))){
                isMainUser = false;
            }else{
                isMainUser = userEntityMap.get(userId).getIsMain().equals(Constant.ONE);
            }
            //获取当前登陆人的数据权限内的人员
            List<String> userIdIn = userModel.getSubIdListByDataPermission(dataPermission, loginUser.getUserId(), loginUser.getCorpid(), BasicConstant.ZERO,false);
            boolean hasTeamDataPer =  CollectionUtils.intersection(userEntityMap.values().stream().map(UserTeamEntity :: getUserId).collect(Collectors.toList()), userIdIn).size() > 0;

            if(!hasMaxPermission && !isMainUser && !hasTeamDataPer){
                return false;
            }else{
                return teamRelatedPojo.getBasicFormEdit();
            }
        }
        return true;
    }



    /**
     * 封装隔离模式下的标签编辑权限
     *  1. 管理员、老板角色、开启数据权限为全公司的人员、团队内负责人或团队内有编辑权限的协同人
     *
     * @param isolationUserPermissionPojo 隔离模式下协同人的可编辑权限
     * @param teamRelatedPojo 中间流转参数实体
     * @param corpid 公司id
     */
    private void packageIsolationEditLabel(IsolationUserPermissionPojo isolationUserPermissionPojo,
                                           TeamRelatedPojo teamRelatedPojo, String corpid) throws XbbException {
        Integer feeType = commonHelp.getCurrentCompanyPackage(corpid);
        if (!Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType())) {
            //非旗舰版套餐是没有编辑标签的功能的
            isolationUserPermissionPojo.setEditLabel(false);
        } else {
            boolean coEditLabel = teamRelatedPojo.getFormEdit();
            boolean mainTag = teamRelatedPojo.getUserCurrentTeamMain();
            if (mainTag || coEditLabel) {
                isolationUserPermissionPojo.setEditLabel(true);
            }else {
                isolationUserPermissionPojo.setEditLabel(false);
            }
        }

    }


    /**
     * 封装隔离模式下编辑团队协同人权限
     *  1. 管理员、老板角色、开启数据权限为全公司的人员、团队内负责人或团队内有编辑权限的协同人
     *  2. 若表单协同人默认权限为只读，此时无法调整
     *
     * @param teamDetailDTO 入参实体
     * @param isolationUserPermissionPojo 权限实体
     * @param teamRelatedPojo 中间流转参数实体
     */
    private void packageIsolationEditCoFormPer(TeamDetailDTO teamDetailDTO, IsolationUserPermissionPojo isolationUserPermissionPojo, TeamRelatedPojo teamRelatedPojo) throws XbbException {
        /*//表单设计那边对可编辑的影响
        Integer feeType = commonHelp.getCurrentCompanyPackage(teamDetailDTO.getCorpid());
        Integer formPermission = coUserFieldAttr.getFormPermission();
        Integer businessType = teamDetailDTO.getBusinessType();
        //如果套餐是旗舰版就按照表单设置那边走，如果套餐是非旗舰版的就按照默认规则走
        if (!Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType())) {
            FormCoUserDefaultPermissionEnum formCoUserDefaultPermissionEnum = FormCoUserDefaultPermissionEnum.getFormPatternEnumByBus(businessType);
            formPermission = formCoUserDefaultPermissionEnum.getDefaultPermissionValue();
        } else {
            if (Objects.isNull(formPermission)) {
                FormCoUserDefaultPermissionEnum formCoUserDefaultPermissionEnum = FormCoUserDefaultPermissionEnum.getFormPatternEnumByBus(businessType);
                formPermission = formCoUserDefaultPermissionEnum.getDefaultPermissionValue();
            }
        }
        if (Objects.equals(formPermission, CoUserPermissionEnum.READ.getPermissionValue())) {
            isolationUserPermissionPojo.setEditCoFormPermission(false);
            return;
        }*/
        Integer feeType = commonHelp.getCurrentCompanyPackage(teamDetailDTO.getCorpid());
        if (!Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType())) {
            isolationUserPermissionPojo.setEditCoFormPermission(false);
            return;
        }
        boolean mainUserTag = teamRelatedPojo.getUserCurrentTeamMain();
        if (mainUserTag) {
            isolationUserPermissionPojo.setEditCoFormPermission(true);
            return;
        }
        if (teamRelatedPojo.getFormEdit()) {
            isolationUserPermissionPojo.setEditCoFormPermission(true);
            return;
        }
        isolationUserPermissionPojo.setEditCoFormPermission(false);
    }

    /**
     * 封装隔离模式下协同人编辑团队的权限
     *     1. 可操作人员：管理员、老板角色、开启数据权限为全公司的人员、团队内负责人或团队内有编辑权限的协同人
     *
     * @param isolationUserPermissionPojo 权限返回实体
     * @param teamRelatedPojo 中间流转参数实体
     */
    private void packageIsolationEditTeam(IsolationUserPermissionPojo isolationUserPermissionPojo, TeamRelatedPojo teamRelatedPojo) throws XbbException {
        //判断是不是管理员、老板角色、开启数据权限为全公司的人员、团队负责人
        boolean mainUserTag = teamRelatedPojo.getUserCurrentTeamMain();
        if (mainUserTag) {
            isolationUserPermissionPojo.setEditTeam(true);
            return;
        }
        //判断是不是团队内有编辑权限的协同人
        if (teamRelatedPojo.getFormEdit()) {
            isolationUserPermissionPojo.setEditTeam(true);
            return;
        }
        isolationUserPermissionPojo.setEditTeam(false);
    }

    /**
     * 隔离模式下移交权限判断
     * （1）首先需要有负责人新增、删除的字段权限
     * （2）1. 管理员、老板角色以及开启数据权限为全公司的人员或团队内负责人 => 得出非超管并且是团队协同人，则没有移交权限，其他情况都是可移交的
     *
     * @param isolationUserPermissionPojo 隔离模式权限实体
     * @param handlerExplainDTO           用于判断字段权限的传参实体
     * @param ownerFieldAttr              负责人字段
     * @param teamRelatedPojo             中间流转参数实体
     * @param teamGroupPojo
     */
    private void packageIsolationChangeMain(IsolationUserPermissionPojo isolationUserPermissionPojo, HandlerExplainDTO handlerExplainDTO,
                                            FieldAttrEntity ownerFieldAttr, TeamRelatedPojo teamRelatedPojo, TeamGroupPojo teamGroupPojo) throws XbbException {
        boolean basicHandleOver = teamRelatedPojo.getBasicHandleOver();
        if (!basicHandleOver) {
            isolationUserPermissionPojo.setChangeMain(false);
            return;
        }
       /*  Boolean haveMainAddPermission = ExplainUtil.advancedOperationHavePermission(ownerFieldAttr, handlerExplainDTO, FieldAdvanceOperationEnum.ADD.getOperation());
        Boolean haveMainDelPermission = ExplainUtil.advancedOperationHavePermission(ownerFieldAttr, handlerExplainDTO, FieldAdvanceOperationEnum.DEL.getOperation());
        if (!haveMainAddPermission || !haveMainDelPermission) {
            isolationUserPermissionPojo.setChangeMain(false);
            return;
        }*/
        UserVO loginUser = handlerExplainDTO.getLoginUser();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(loginUser, userEntity);
        Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.SAAS, handlerExplainDTO.getBusinessType(), 0L);
        if (!Objects.equals(dataPermission, DataPermissionEnum.ALL.getCode())) {
            // 非全公司数据权限
            if (!teamRelatedPojo.getBasicTeamMain()) {
                // 非团队负责人

                // 操作人有原负责人的数据权限
                String originUserId = teamGroupPojo.getMainUserArr().get(0).getTeamUserPojo().getUserId();

                List<String> userIdIn = userModel.getSubIdListByDataPermission(dataPermission, loginUser.getUserId(), loginUser.getCorpid(), BasicConstant.ZERO,false);

                if (!userIdIn.contains(originUserId)) {
                    isolationUserPermissionPojo.setChangeMain(false);
                    return;
                } else {

                    Map<String, Integer> coUserMap = teamGroupPojo.getCoopUserArr().stream().collect(Collectors.toMap(v -> v.getTeamUserPojo().getUserId(), v -> v.getTeamUserPojo().getFormPermission(), (v1, v2) -> v1));

                    if (coUserMap.containsKey(loginUser.getUserId())) {
                        Integer permission = coUserMap.get(loginUser.getUserId());

                        // 登录人是协同人且有编辑权限
                        if (Objects.equals(CoUserPermissionEnum.EDIT.getPermissionValue(), permission)) {
                            isolationUserPermissionPojo.setChangeMain(true);
                            return;
                        } else {
                            isolationUserPermissionPojo.setChangeMain(false);
                            return;
                        }
                    } else {
                        isolationUserPermissionPojo.setChangeMain(true);
                        return;
                    }
                }

            }
        }


    }



    /**
     * 获取当前人在当前团队的负责人权限或者是不是超管权限,跟getUserCurrentTeamMainPer方法不同，主要加了表单权限过滤
     *
     * @param teamDetailDTO 团队详情入参
     * @param mainUserArr 隔离模式下团队负责人，按照目前设计，只可能会有一个负责人
     * @return
     */
    private boolean getUserCurrentTeamMainPerSen(TeamDetailDTO teamDetailDTO, List<MainUserPojo> mainUserArr, Boolean hasMaxPermission) {
        UserVO loginUser = teamDetailDTO.getLoginUser();
        String userId = loginUser.getUserId();
        if (hasMaxPermission) {
            return true;
        }
        for (MainUserPojo mainUserPojo : mainUserArr) {
            if (Objects.equals(userId, mainUserPojo.getTeamUserPojo().getUserId())) {
                return true;
            }
        }
        return false;
    }


    /**
     * 封装隔离模式下的协同人权限
     *      i. 删除协同人 -》可操作人员：管理员、老板角色、开启数据权限为全公司的人员、团队内负责人或团队内有编辑权限的协同人；同时有协同人字段删除权限人员
     *
     * @param coUserFieldAttr 协同人字段
     * @param handlerExplainDTO
     * @param isolationUserPermissionPojo 隔离模式下的权限
     * @param teamRelatedPojo 中间流转参数实体
     */
    private void packageIsonlationCoPermission(FieldAttrEntity coUserFieldAttr, HandlerExplainDTO handlerExplainDTO,
                                               IsolationUserPermissionPojo isolationUserPermissionPojo, TeamRelatedPojo teamRelatedPojo) throws XbbException {
        Boolean coAdd = false;
        Boolean coDel = false;
        //高级权限设置或者共享权限满足一个，就可编辑
        Boolean haveCoUserAddPermission = ExplainUtil.advancedOperationHavePermission(coUserFieldAttr, handlerExplainDTO, FieldAdvanceOperationEnum.ADD.getOperation());
        Boolean haveCoUserDelPermission = ExplainUtil.advancedOperationHavePermission(coUserFieldAttr, handlerExplainDTO, FieldAdvanceOperationEnum.DEL.getOperation());
        Boolean teamMain = teamRelatedPojo.getUserCurrentTeamMain();
        Boolean teamCo = false;
        if (!teamMain) {
            //代表当前人不是负责人以及超管，才会校验协同人权限
            teamCo = teamRelatedPojo.getFormEdit();
        }
        if (teamMain && haveCoUserAddPermission) {
            coAdd = true;
        }else if (teamCo && haveCoUserAddPermission) {
            coAdd = true;
        }
        if (teamMain && haveCoUserDelPermission) {
            coDel = true;
        }else if (teamCo && haveCoUserDelPermission) {
            //是团队里面的协同人，历史协同人也没有团队
            coDel = true;
        }
        isolationUserPermissionPojo.setCoAdd(coAdd);
        isolationUserPermissionPojo.setCoDel(coDel);
    }





    /**
     * 获取当前人在当前团队的负责人权限或者是不是超管权限
     *
     * @param teamDetailDTO 团队详情入参
     * @param mainUserArr 隔离模式下团队负责人，按照目前设计，只可能会有一个负责人
     * @param teamRelatedPojo 中间流转参数实体
     * @return
     */
    private boolean getUserCurrentTeamMainPer(TeamDetailDTO teamDetailDTO, List<MainUserPojo> mainUserArr, TeamRelatedPojo teamRelatedPojo, Boolean hasMaxPermission) throws XbbException {
        UserVO loginUser = teamDetailDTO.getLoginUser();
        String userId = loginUser.getUserId();
        boolean basicFormEdit = teamRelatedPojo.getBasicFormEdit();
        if (!basicFormEdit) {
            return false;
        }
        if (hasMaxPermission) {
            return true;
        }
        for (MainUserPojo mainUserPojo : mainUserArr) {
            if (Objects.equals(userId, mainUserPojo.getTeamUserPojo().getUserId())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 封装标签信息返回
     *
     * @param userTeamEntities
     * @return 返回一个用户id与标签列表对应关系的一个map,就是当前用户有哪些标签
     */
    private Map<String, List<UserLabelPojo>>  packageUserLabelInfo(TeamDetailDTO teamDetailDTO, List<UserTeamEntity> userTeamEntities) {
        String corpid = teamDetailDTO.getCorpid();
        //userid -> sysLabelIdList , 保存最终的用户系统标签id
        Map<String, List<Long>> userSysLabel = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        //userid -> formLabelIdList , 保存最终的用户表单标签id
        Map<String, List<Long>> userFormLabel = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<String> userIdList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(userTeamEntities)){
            userIdList = userTeamEntities.stream().map(UserTeamEntity::getUserId).collect(Collectors.toList());
        }
        //List<UserEntity> userSysList = userModel.getByUserId(userIdList, corpid);
        //Map<String, UserEntity> userEntityMap = userSysList.stream().collect(Collectors.toMap(UserEntity::getUserId, v -> v));
        for (UserTeamEntity userTeamEntity : userTeamEntities) {
            JSONArray labels = userTeamEntity.getLabels();
            String userId = userTeamEntity.getUserId();
            if (Objects.nonNull(labels) && labels.size() > BasicConstant.ZERO) {
                for (int i = 0; i < labels.size(); i++) {
                    JSONObject jsonObject = labels.getJSONObject(i);
                    Integer type = jsonObject.getInteger(BasicConstant.TYPE);
                    if (Objects.equals(LabelTypeEnum.SYS_LABEL.getType(), type)) {
                        userSysLabel.computeIfAbsent(userId, v -> new ArrayList<>()).add(jsonObject.getLong(BasicConstant.ID));
                    }else {
                        userFormLabel.computeIfAbsent(userId,v -> new ArrayList<>()).add(jsonObject.getLong(BasicConstant.ID));
                    }
                }
            }
        }
        //查询所有的sys标签
        Set<Long> sysLabelList = userSysLabel.values().stream().flatMap(List::stream).collect(Collectors.toSet());
        List<SysLabelEntity> sysLabelEntityList = sysLabelModel.getByLabelIdIn(corpid, sysLabelList);
        Map<Long, UserLabelPojo> sysLabelMap = sysLabelEntityList.stream().collect(Collectors.toMap(SysLabelEntity::getId, v -> new UserLabelPojo(v.getId(), v.getColor(), v.getName(), LabelTypeEnum.SYS_LABEL.getType())));
        //查询所有的form标签
        List<Long> formLabelList = userFormLabel.values().stream().flatMap(List::stream).collect(Collectors.toList());
        List<FormLabelEntity> formLabelEntityList = formLabelModel.getByLabelIdIn(corpid, formLabelList);
        Map<Long, UserLabelPojo> formLabelMap = formLabelEntityList.stream().collect(Collectors.toMap(FormLabelEntity::getId, v -> new UserLabelPojo(v.getId(), v.getColor(), v.getName(), LabelTypeEnum.FORM_LABEL.getType())));
        //封装一个团队里面成员id和标签的map
        //key是用户id
        Map<String, List<UserLabelPojo>> userIdLabelMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (String userId : userIdList) {
            userIdLabelMap.put(userId,new ArrayList<>());
            List<Long> sysLabels = userSysLabel.get(userId);
            if(CollectionUtils.isNotEmpty(sysLabels)){
                sysLabels.forEach(v -> {
                    userIdLabelMap.get(userId).add(sysLabelMap.get(v));
                });
            }
            List<Long> formLabels = userFormLabel.get(userId);
            if(CollectionUtils.isNotEmpty(formLabels)){
                formLabels.forEach(v -> {
                    userIdLabelMap.get(userId).add(formLabelMap.get(v));
                });
            }
        }

        return userIdLabelMap;
    }

    /**
     * Description: 校验团队数据（tab）
     * @param teamVerifyDTO
     * @return com.xbongbong.pro.team.TeamAfterVerifyDTO
     * @throws
     * @author 魏荣杰
     * @date 2022/1/5 20:17
     * @since
     */
    protected TeamAfterVerifyDTO verifyFromTab(TeamVerifyDTO teamVerifyDTO) throws XbbException {
        String corpid = teamVerifyDTO.getCorpid();
        List<Long> dataIdIn = teamVerifyDTO.getDataId();
        Long formId = teamVerifyDTO.getFormId();
        Integer saasMark = teamVerifyDTO.getSaasMark();
        Integer businessType = teamVerifyDTO.getBusinessType();
        Integer distributorMark = teamVerifyDTO.getDistributorMark();
        Integer subBusinessType = teamVerifyDTO.getSubBusinessType();
        // 需要判权的用户id
        String userId = teamVerifyDTO.getUserId();
        // 主数据创建人id
        String creatorId = teamVerifyDTO.getCreatorId();
        // 需要判权的用户/当前操作人
        UserVO loginUser = teamVerifyDTO.getLoginUser();
        // 要添加的负责人
        Set<String> newAddMainUserList = CollectionUtils.isEmpty(teamVerifyDTO.getNewAddMainUserList()) ? new HashSet<>() : teamVerifyDTO.getNewAddMainUserList();
        // 要删除的负责人
        Set<String> newDelMainUserList = CollectionUtils.isEmpty(teamVerifyDTO.getNewDelMainUserList()) ? new HashSet<>() : teamVerifyDTO.getNewDelMainUserList();
        // 要添加的协同人
        Set<String> newAddCoUserList = CollectionUtils.isEmpty(teamVerifyDTO.getNewAddCoUserList()) ? new HashSet<>() : teamVerifyDTO.getNewAddCoUserList();
        // 要删除的协同人
        Set<String> newDelCoUserList = CollectionUtils.isEmpty(teamVerifyDTO.getNewDelCoUserList()) ? new HashSet<>() : teamVerifyDTO.getNewDelCoUserList();
        // 是否继承
        Boolean isInheritance = teamVerifyDTO.getIsInheritance();
        //批量标识
        Integer batchTag = teamVerifyDTO.getBatchTag();
        // 来自退回公海池操作
        Boolean fromBackPublic = teamVerifyDTO.getFromBackPublic();

        TeamAfterVerifyDTO teamAfterVerifyDTO = new TeamAfterVerifyDTO();
        teamAfterVerifyDTO.setLoginUser(loginUser);
        teamAfterVerifyDTO.setCorpid(corpid);
        teamAfterVerifyDTO.setFormId(formId);
        teamAfterVerifyDTO.setSaasMark(saasMark);
        teamAfterVerifyDTO.setBusinessType(businessType);
        teamAfterVerifyDTO.setDistributorMark(distributorMark);
        teamAfterVerifyDTO.setDataId(dataIdIn);
        teamAfterVerifyDTO.setIsInheritance(isInheritance);
        teamAfterVerifyDTO.setTeamUserId(teamVerifyDTO.getTeamUserId());
        teamAfterVerifyDTO.setFromDetail(teamVerifyDTO.getFromDetail());
        teamAfterVerifyDTO.setTeamName(teamVerifyDTO.getTeamName());
        teamAfterVerifyDTO.setOperateTag(teamVerifyDTO.getOperateTag());
        teamAfterVerifyDTO.setFromBackPublic(teamVerifyDTO.getFromBackPublic());
        if (Objects.nonNull(teamVerifyDTO.getChangeUserId())) {
            teamAfterVerifyDTO.setChangeUserId(teamVerifyDTO.getChangeUserId());
        }
        // 获取负责人/协同人字段解释
        TeamFieldExplainPOJO teamFieldExplainPOJO = teamUserHelp.getTeamFieldExplain(corpid, formId, businessType);
        // 负责人解释
        FieldAttrEntity ownerField = teamFieldExplainPOJO.getOwnerField();
        Integer feeType = commonHelp.getCurrentCompanyPackage(corpid);
        if (Objects.nonNull(ownerField)) {
            Integer multiple = ownerField.getMultiple();
            if (Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType())) {
                if (Objects.isNull(multiple)) {
                    FormOwnerUniqueEnum formOwnerUniqueEnum = FormOwnerUniqueEnum.getFormOwnerUniqueByBus(businessType);
                    if (Objects.nonNull(formOwnerUniqueEnum)) {
                        ownerField.setMultiple(formOwnerUniqueEnum.getValue());
                    }
                }
            }else {
                FormOwnerUniqueEnum formOwnerUniqueEnum = FormOwnerUniqueEnum.getFormOwnerUniqueByBus(businessType);
                if (Objects.nonNull(formOwnerUniqueEnum)) {
                    ownerField.setMultiple(formOwnerUniqueEnum.getValue());
                }
            }
        }

        // 协同人解释
        FieldAttrEntity coUserField = teamFieldExplainPOJO.getCoUserField();
        //协同人可编辑权限
        Integer formPermission = null;
        if (Objects.nonNull(coUserField)) {
            formPermission = coUserField.getFormPermission();
            if (Objects.isNull(formPermission)) {
                formPermission = FormCoUserDefaultPermissionEnum.getDefaultPerByBus(businessType);
            }
        }
        // 共享/隔离处理
        // 获取共享/隔离配置
        FormTeamSetEntity formTeamSetEntity = formTeamSetHelp.getFormTeamSet(corpid, formId, saasMark, businessType, distributorMark);

        // 有共享/隔离的业务
        Integer model = formTeamSetEntity.getModel();
        //非旗舰版套餐默认走通用规则，旗舰版套餐就需要各种判断了。以及未设置过共享或隔离的走默认规则
        if (Objects.isNull(model) || !Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType())) {
            model = FormDefaultPatternEnum.getModelValueByBusinessType(businessType);
            formTeamSetEntity.setModel(model);
        }
        // 获取老的团队数据
        TeamUserListPOJO teamUserListPOJO = getTeamOldUserList(corpid, formId, businessType, subBusinessType, dataIdIn, model);
        // 老的团队所有成员
        Map<Long, Set<String>> oldUserMap = teamUserListPOJO.getOldUserMap();
        // 老的负责人和协同人
        Map<Long, Set<String>> oldMainUserMap = teamUserListPOJO.getOldMainUserMap();
        Map<Long, Set<String>> oldCoUserMap = teamUserListPOJO.getOldCoUserMap();
        Map<Long, Map<String, Set<String>>> oldTeamCoUserMap = teamUserListPOJO.getOldTeamCoUserMap();

        List<PaasFormDataEntityExt> formDataEntityExts = getDataByDataIdList(dataIdIn, businessType, saasMark, formId, corpid, "id,data,creator_id");
        Map<Long, String> dataIdAndCreatorIdMap = formDataEntityExts.stream().collect(Collectors.toMap(PaasFormDataEntity::getId, PaasFormDataEntity::getCreatorId));

        //获取主数据相关集合，主要用于提示使用
        Map<Long, String> nameOrSeriNoMap = new HashMap<>();
        Map<Long, PaasFormDataEntity> paasFormDataEntityExtMap = getEntityMap(businessType, dataIdIn, corpid, nameOrSeriNoMap, saasMark);
        Map<String, Set<String>> addMainUserMap = new HashMap<>();
        Map<String, Set<String>> addCoUserMap = new HashMap<>();
        Map<String, Set<String>> delMainUserMap = new HashMap<>();
        Map<String, Set<String>> delCoUserMap = new HashMap<>();
        Map<String, Set<String>> updateCoToMainUserMap = new HashMap<>();
        Map<String, Set<String>> updateMainToCoUserMap = new HashMap<>();
        Map<String, Map<String, Set<String>>> changeTeamMainUserMap = new HashMap<>();
        List<TeamBatchPojo> teamBatchPojos = new ArrayList<>();

        //公海里的数据，不允许移交
        if(Objects.equals(teamVerifyDTO.getOperateTag(), UserTeamOperateTagEnum.HANDOVER.getOperateTag())){
            if(Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())){
                for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntityExtMap.values()) {
                    boolean trueCustomerPublicTag = Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) && Objects.equals(paasFormDataEntity.getData().getInteger(ManagementBaseEnum.IS_PUBLIC.getAttr()), PublicEnum.PUBLIC.getCode());
                    boolean trueCluePublicTag = Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode()) && Objects.equals(paasFormDataEntity.getData().getInteger(ClueEnum.IS_PUBLIC.getAttr()), PublicEnum.PUBLIC.getCode());
                    if(Objects.nonNull(paasFormDataEntity.getData()) && (trueCustomerPublicTag || trueCluePublicTag)){
                        Long dataId = paasFormDataEntity.getDataId();
                        //移除报错数据，封装异常
                        dataIdIn.removeIf(dataId::equals);
                        TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271037.getCode(), UserTeamErrorCodeEnum.API_ERROR_271037.getMsg(),
                                nameOrSeriNoMap.get(dataId), UserTeamOperateTagEnum.HANDOVER.getName(),dataId);
                        teamBatchPojos.add(teamBatchPojo);
                    }
                }
            }
        }

        for (Long dataId : dataIdIn) {
            Set<String> oldMainUserList = oldMainUserMap.getOrDefault(dataId, new HashSet<>());
            Set<String> oldCoUserList = oldCoUserMap.getOrDefault(dataId, new HashSet<>());
            Map<String, Set<String>> oldTeamCoUserRelMap = oldTeamCoUserMap.getOrDefault(dataId, new HashMap<>());

            if (!teamVerifyDTO.getFromApproval()) {

                // 权限校验
                TeamBatchPojo teamBatchPojo = verifyPermissions(corpid, userId, dataIdAndCreatorIdMap.getOrDefault(dataId, null), loginUser, newAddMainUserList, newDelMainUserList, newAddCoUserList, newDelCoUserList, ownerField, coUserField, oldMainUserList, oldCoUserList, isInheritance, fromBackPublic, teamVerifyDTO.getPaasOwnUserFromOwnTag(),
                        nameOrSeriNoMap, dataId, teamVerifyDTO.getOperateTag());

                // 报错处理
                if (Objects.nonNull(teamBatchPojo)) {
                    teamBatchPojos.add(teamBatchPojo);

                    continue;
                }
            }

            TeamModelProcessMidPOJO teamModelProcessMidPOJO = new TeamModelProcessMidPOJO(model, corpid, dataId, businessType, newAddMainUserList, null, null, newDelMainUserList, newAddCoUserList, newDelCoUserList, isInheritance, ownerField, coUserField,
                    oldMainUserList, oldCoUserList, loginUser, teamVerifyDTO.getFromDetail(), teamVerifyDTO.getOriginUserId(), teamVerifyDTO.getChangeUserId(),
                    nameOrSeriNoMap, oldTeamCoUserRelMap, fromBackPublic, teamVerifyDTO.getOperateTag(), teamVerifyDTO.getSaasMark(),teamVerifyDTO.getTeamUserId(),teamVerifyDTO.getPlatform(), teamVerifyDTO.getFromCover(), formId);
            TeamAfterModeProcessPOJO teamAfterModeProcessPOJO = shareAndIsolationModeProcess(teamModelProcessMidPOJO);

            // 报错处理
            TeamBatchPojo batchPojo = teamAfterModeProcessPOJO.getTeamBatchPojo();
            if (Objects.nonNull(batchPojo)) {
                teamBatchPojos.add(batchPojo);
                continue;
            }

            addMainUserMap.put(String.valueOf(dataId), teamAfterModeProcessPOJO.getAddMainUserList());
            addCoUserMap.put(String.valueOf(dataId), teamAfterModeProcessPOJO.getAddCoUserList());
            delMainUserMap.put(String.valueOf(dataId), teamAfterModeProcessPOJO.getDelMainUserList());
            delCoUserMap.put(String.valueOf(dataId), teamAfterModeProcessPOJO.getDelCoUserList());
            updateCoToMainUserMap.put(String.valueOf(dataId), teamAfterModeProcessPOJO.getCoToMainUserList());
            changeTeamMainUserMap.put(String.valueOf(dataId), teamAfterModeProcessPOJO.getChangeTeamMainUserMap());

        }

        // 校验公海池规则
        //checkPublicRule(corpid, dataIdIn, businessType, addMainUserMap);
        teamAfterVerifyDTO.setAddMainUserMap(addMainUserMap);
        teamAfterVerifyDTO.setAddCoUserMap(addCoUserMap);
        teamAfterVerifyDTO.setDelMainUserMap(delMainUserMap);
        teamAfterVerifyDTO.setDelCoUserMap(delCoUserMap);
        teamAfterVerifyDTO.setUpdateToMainUserMap(updateCoToMainUserMap);
        teamAfterVerifyDTO.setChangeTeamMainUserMap(changeTeamMainUserMap);
        teamAfterVerifyDTO.setUpdateToCoUserMap(updateMainToCoUserMap);
        teamAfterVerifyDTO.setFormTeamSetEntity(formTeamSetEntity);
        teamAfterVerifyDTO.setTeamBatchPojos(teamBatchPojos);
        teamAfterVerifyDTO.setPaasFormDataEntityExtMap(paasFormDataEntityExtMap);
        teamAfterVerifyDTO.setEditFormPermission(formPermission);
        teamAfterVerifyDTO.setBatchTag(batchTag);
        teamAfterVerifyDTO.setFromCheckRepeatForm(teamVerifyDTO.getFromCheckRepeatForm());
        return teamAfterVerifyDTO;
    }

    protected void inheritanceSave(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {

    }

    protected void dynamic(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {
        // 动态

    }



    /**
     * 由子类实现
     * @param corpid
     * @param businessType
     * @param saasMark
     * @param dataId
     * @return
     * @throws XbbException
     */
    protected PaasFormDataEntityExt getData(String corpid, Integer businessType, Integer saasMark, Long dataId) throws XbbException {
        return null;
    }

    /**
     * 由子类实现
     * @param dataIdList
     * @param businessType
     * @param saasMark
     * @param formId
     * @param corpid
     * @param columns
     * @return
     * @throws XbbException
     */
    protected List<PaasFormDataEntityExt> getDataByDataIdList(Collection<Long> dataIdList, Integer businessType, Integer saasMark, Long formId, String corpid, String columns) throws XbbException {
        return null;
    }

    /**
     * 由子类实现
     * @param businessType
     * @param dataIdList
     * @param corpid
     * @param nameOrSeriNoMap
     * @param saasMark
     * @return
     * @throws XbbException
     */
    protected Map<Long, PaasFormDataEntity> getEntityMap(Integer businessType, List<Long> dataIdList, String corpid, Map<Long, String> nameOrSeriNoMap, Integer saasMark) throws XbbException {
        return null;
    }


    protected Boolean checkPermission(PaasFormDataEntityExt paasFormDataEntityExt, Integer saasMark, UserVO loginUser, Integer businessType, Long menuId, String corpid) throws XbbException {
        return false;
    }

    /**
     * Description: 判断团队数据变化，哪个团队数据需要es等待，返回为map，value为true的key需要等待
     * @param teamAfterFormatDTO
     * @return java.util.Map<java.lang.String,java.lang.Boolean>
     * @throws
     * @author 魏荣杰
     * @date 2023/4/18 15:57
     * @since
     */
    protected LinkedHashMap<String, Integer> judgeTeamEsWait(TeamAfterFormatDTO teamAfterFormatDTO) {
        List<UserTeamEntity> addUserTeamList = teamAfterFormatDTO.getAddUserTeamList();
        List<UserTeamEntity> delUserTeamList = teamAfterFormatDTO.getDelUserTeamList();
        List<UserTeamEntity> updateUserToMainTeamList = teamAfterFormatDTO.getUpdateUserToMainTeamList();
        List<UserTeamEntity> updateUserToCoTeamList = teamAfterFormatDTO.getUpdateUserToCoTeamList();
        List<UserTeamEntity> updateUserTeamMainList = teamAfterFormatDTO.getUpdateUserTeamMainList();
        Map<String, Integer> typeSizeMap = new HashMap();
        typeSizeMap.put(TeamMembersConstant.ADD_USER, addUserTeamList.size());
        typeSizeMap.put(TeamMembersConstant.DEL_USER, delUserTeamList.size());
        typeSizeMap.put(TeamMembersConstant.TO_MAIN_USER, updateUserToMainTeamList.size());
        typeSizeMap.put(TeamMembersConstant.TO_CO_USER, updateUserToCoTeamList.size());
        typeSizeMap.put(TeamMembersConstant.UPDATE_USER, updateUserTeamMainList.size());
        return typeSizeMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(
                        Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldV, newV) -> oldV, LinkedHashMap::new)
                );
    }
}
